我需要在固定的时间间隔安排一个任务。在长时间间隔(例如每8小时一次)的支持下,我如何做到这一点?
我目前使用java.util.Timer.scheduleAtFixedRate。java.util.Timer.scheduleAtFixedRate支持长时间间隔吗?
我需要在固定的时间间隔安排一个任务。在长时间间隔(例如每8小时一次)的支持下,我如何做到这一点?
我目前使用java.util.Timer.scheduleAtFixedRate。java.util.Timer.scheduleAtFixedRate支持长时间间隔吗?
当前回答
我使用Spring Framework的特性。(spring-context jar或maven依赖)。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTaskRunner {
@Autowired
@Qualifier("TempFilesCleanerExecution")
private ScheduledTask tempDataCleanerExecution;
@Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
public void performCleanTempData() {
tempDataCleanerExecution.execute();
}
}
ScheduledTask是我自己与自定义方法execute的接口,我将其作为我的计划任务调用。
其他回答
使用ScheduledExecutorService:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
如果您的应用程序已经在使用Spring框架,那么您已经内置了调度
在java.util中有一个ScheduledFuture类。同时,它可能会帮助你。
您尝试过使用注释的Spring Scheduler吗?
@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
//body can be another method call which returns some value.
}
XML也可以做到这一点。
<task:scheduled-tasks>
<task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
<task:scheduled-tasks>
试试这种方式——>
首先创建一个运行任务的类TimeTask,它看起来像:
public class CustomTask extends TimerTask {
public CustomTask(){
//Constructor
}
public void run() {
try {
// Your task process
} catch (Exception ex) {
System.out.println("error running thread " + ex.getMessage());
}
}
}
然后在main类中实例化任务,并定期运行它,从一个精确的日期开始:
public void runTask() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timer time = new Timer(); // Instantiate Timer Object
// Start running the task on Monday at 15:40:00, period is set to 8 hours
// if you want to run the task immediately, set the 2nd parameter to 0
time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}