下次凌晨1点获取日期

时间:2010-11-17 13:42:30

标签: java date datetime calendar

为了运行后台服务,我想安排一个线程,每天凌晨1点运行。我怎样才能在java中获得这个日期?

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, HOUR_OF_EXECUTION);
Date date = cal.getTime();

没用。

1 个答案:

答案 0 :(得分:5)

你应该去Quartz

OR

Timer timer = new Timer();
final Callable c = callable;
TimerTask task = new TimerTask() {
    public void run() {
            c.call();
    }
}
t.scheduleAtFixedRate(task, firstExecuteDate, 86400000); // every day  

相应地给出firstExecuteDate,你的事情已经完成了,更多的是下次执行 - 现在

获取下午1点的日期。

Calendar cal  = Calendar.getInstance();
Calendar calAtOne  = Calendar.getInstance();
calAtOne.set(Calendar.HOUR_OF_DAY,13);
calAtOne.set(Calendar.MINUTE,00);
calAtOne.set(Calendar.SECOND,00);

if(calAtOne.after(cal)){
    return calAtOne;
}else{
    cal.add(Calendar.DATE,1);
    cal.set(Calendar.HOUR_OF_DAY,13);
    cal.set(Calendar.MINUTE,00);
    cal.set(Calendar.SECOND,00);
    return cal;
}

然后减去currentMillis - (nextExecDate returned By above code)