我需要在固定的时间间隔安排一个任务。在长时间间隔(例如每8小时一次)的支持下,我如何做到这一点?
我目前使用java.util.Timer.scheduleAtFixedRate。java.util.Timer.scheduleAtFixedRate支持长时间间隔吗?
我需要在固定的时间间隔安排一个任务。在长时间间隔(例如每8小时一次)的支持下,我如何做到这一点?
我目前使用java.util.Timer.scheduleAtFixedRate。java.util.Timer.scheduleAtFixedRate支持长时间间隔吗?
当前回答
每一秒都做点什么
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
//code
}
}, 0, 1000);
其他回答
你应该看看Quartz,它是一个java框架,适用于EE和SE版本,并允许定义作业来执行特定的时间
这两个类可以一起工作来安排一个周期性任务:
计划任务
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
运行定时任务
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
参考https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
我使用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的接口,我将其作为我的计划任务调用。
如果您的应用程序已经在使用Spring框架,那么您已经内置了调度
使用谷歌Guava AbstractScheduledService如下所示:
public class ScheduledExecutor extends AbstractScheduledService {
@Override
protected void runOneIteration() throws Exception {
System.out.println("Executing....");
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
}
@Override
protected void startUp() {
System.out.println("StartUp Activity....");
}
@Override
protected void shutDown() {
System.out.println("Shutdown Activity...");
}
public static void main(String[] args) throws InterruptedException {
ScheduledExecutor se = new ScheduledExecutor();
se.startAsync();
Thread.sleep(15000);
se.stopAsync();
}
}
如果你有更多这样的服务,那么在ServiceManager中注册所有的服务会很好,因为所有的服务都可以同时启动和停止。阅读这里了解更多关于ServiceManager的信息。