在Java中安排特定时间的东西?

时间:2014-03-31 19:16:04

标签: java date timer scheduled-tasks

我需要每天在特定时间运行计划任务。

到目前为止,我有这个:

Date timeToRun = new Date(System.currentTimeMillis());
Timer myTimer = new Timer();

myTimer.schedule(new TimerTask() {
    public void run() {
        //Method to run
    }
}, timeToRun);

如何将timeToRun设置为特定时间?这样我就可以在任何特定的日期运行这个代码,它会在正确的时间运行任务;例如每天晚上7:30。

4 个答案:

答案 0 :(得分:2)

如果您尝试使用特定时间创建日期对象,则代码为

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,19);
cal.set(Calendar.MINUTE,30);

Date timeoRun = cal.getTime();

编辑以满足评论中发布的要求 -

if(System.currentTimeMillis()>timeToRun.getTime()){
    cal.add(Calendar.DATE,1);
}
timeToRun = cal.getTime();
System.out.println(timeToRun);

在上面的代码中,检查当前时间是否大于计算时间,如果是,则增加日期。

答案 1 :(得分:0)

import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;

public final class FetchMail extends TimerTask {

/** Construct and use a TimerTask and Timer. */
public static void main (String... arguments ) {
TimerTask fetchMail = new FetchMail();
//perform the task once a day at 4 a.m., starting tomorrow morning
//(other styles are possible as well)
Timer timer = new Timer();
timer.scheduleAtFixedRate(fetchMail, getTomorrowMorning4am(), fONCE_PER_DAY);
}

/**
* Implements TimerTask's abstract run method.
*/
@Override public void run(){
//toy implementation
System.out.println("Fetching mail...");
}

// PRIVATE

//expressed in milliseconds
private final static long fONCE_PER_DAY = 1000*60*60*24;

private final static int fONE_DAY = 1;
private final static int fFOUR_AM = 4;
private final static int fZERO_MINUTES = 0;

private static Date getTomorrowMorning4am(){
Calendar tomorrow = new GregorianCalendar();
tomorrow.add(Calendar.DATE, fONE_DAY);
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR),
tomorrow.get(Calendar.MONTH),
tomorrow.get(Calendar.DATE),
fFOUR_AM,
fZERO_MINUTES
);
return result.getTime();

}


}

此处,每天凌晨4点开始执行一项任务,从明天早上开始使用Timer和TimerTask。

答案 2 :(得分:0)

这是一个更多的争论

myTimer.schedule(new TimerTask() {
    public void run() {
        //Method to run
    }
}, timeToRun, 24*60*60*1000);

答案 3 :(得分:0)

ScheduledExecutorService的

{5}}接口已添加到Java 5中以满足您的需要。

替代Timer。在选择之前,你应该研究两者都有利有弊。

特别要注意......

  

如果任务的任何执行遇到异常,则后续执行将被禁止。

ScheduledExecutorService中所述,如果抛出任何异常,服务将以静默方式退出运行任何更多的执行。我使用的一种解决方法是使用常规try-catch(和log)包装正在运行的整个代码,以获得最通用的异常。