我需要根据用户输入的时间和天数安排任务。这些任务每周都会重复,根据复选框值我需要在那些日子设置它们。
例如,现在是星期三的第六个15:40 UTC + 2。如果用户想要在每个星期三的12:00安排任务,我想在11月13日的12:00以秒为单位获得时间。如果任务设置为每周三16:00安排,我想要今天的时间。计划在每个星期四运行的任务导致明天的毫秒表示。所以,基本上是最接近的日期。我如何在Java中实现它?
答案 0 :(得分:1)
最简单,也许是最狡猾的答案是使用Quartz。 :)
您当然可以编写自己的调度程序,但这不是一项简单的任务。
修改强>
要获取日期,您可以在日历上使用add()方法。 要以ms为单位获取时间,可以使用方法getTimeInMillis()。
如果你想要一个更容易(并且我的拙见,更直观)的方法,你可以使用joda-time(http://www.joda.org/joda-time/)的DateTime类,它更优雅,不可变和时区感知。 :)
祝你好运。答案 1 :(得分:1)
已弃用的Date.getDay()功能解释了如何使用日历执行此操作。 (如果您真的想要使用它,尽管被弃用,日期仍然有效。)
Calendar.get(Calendar.DAY_OF_WEEK);
在流程方面,您将有一个类将事件的一周中的某一天存储为int和时间。
然后,您将评估今天的日期和时间:
您可能还需要检查夏令时。
答案 2 :(得分:0)
感谢您的回答。 Compass的答案是正确的,我在Java中创建了以下实现:
public static long nextDate(int day, int hour, int minute) {
// Initialize the Calendar objects
Calendar current = Calendar.getInstance();
Calendar target = Calendar.getInstance();
// Fetch the current day of the week.
// Calendar class weekday indexing starts at 1 for Sunday, 2 for Monday etc.
// Change it to start from zero on Monday continueing to six for Sunday
int today = target.get(Calendar.DAY_OF_WEEK) - 2;
if(today == -1) today = 7;
int difference = -1;
if(today <= day) {
// Target date is this week
difference = day - today;
} else {
// Target date is passed already this week.
// Let's get the date next week
difference = 7 - today + day;
}
// Setting the target hour and minute
target.set(Calendar.HOUR_OF_DAY, hour);
target.set(Calendar.MINUTE, minute);
target.set(Calendar.SECOND, 0);
// If difference == 0 (target day is this day), let's check that the time isn't passed today.
// If it has, set difference = 7 to get the date next week
if(difference == 0 && current.getTimeInMillis() > target.getTimeInMillis()) {
difference = 7;
}
// Adding the days to the target Calendar object
target.add(Calendar.DATE, difference);
// Just for debug
System.out.println(target.getTime());
// Return the next suitable datetime in milliseconds
return target.getTimeInMillis();
}