我需要安排一个任务以固定的时间间隔运行。如何在支持长时间间隔的情况下执行此操作(例如每8小时一次)?
我目前正在使用java.util.Timer.scheduleAtFixedRate
。这个方法是否支持长时间间隔?
我需要安排一个任务以固定的时间间隔运行。如何在支持长时间间隔的情况下执行此操作(例如每8小时一次)?
我目前正在使用java.util.Timer.scheduleAtFixedRate
。这个方法是否支持长时间间隔?
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
试试这种方法 ->
首先创建一个运行您任务的 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());
}
}
}
然后在主类中,您实例化任务并定期运行它,从指定的日期开始:
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));
}
使用Google 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的信息。
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
//code
}
}, 0, 1000);
这两个类可以共同工作来安排定期任务:
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/
这篇文章介绍了如何在Java中定期运行任务。在Java中,可以使用ScheduledExecutorService来创建一个计划任务,并使用不同的方法来安排任务的执行频率,例如每个固定的延迟时间,或者在特定的日期和时间运行。此外,文章还提供了代码示例来帮助您更好地理解如何实现定期任务。我使用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方法,我将其称为我的计划任务。
您还可以使用JobRunr,这是一个易于使用和开源Java计划程序。
要使用JobRunr每8小时安排一个任务,则需要使用以下代码:
BackgroundJob.scheduleRecurrently(Duration.ofHours(8), () -> yourService.methodToRunEvery8Hours());
@Recurring
注解:
public class YourService {
@Recurring(interval="PT8H")
public void methodToRunEvery8Hours() {
// your business logic
}
}
JobRunr还内置了一个仪表板,可让您跟踪作业的运行状况。
TimeUnit
适用于initialDelay
和period
。当夏令时开始时,每24小时运行一次将被打乱,但是DAYS
的TimeUnit
不允许您指定细粒度的initialDelay
。(我认为内部的ScheduledExecutorService实现会将DAYS
转换为纳秒)。 - Sam Barnum