Imr*_*han 13 java scheduling scheduled-tasks
我正在开发一种服务,假设每小时开始重复一小时(下午1:00,下午2:00,下午3:00等).
我试过跟随,但它有一个问题,我第一次必须在小时开始运行程序,然后这个调度程序将重复它.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleWithFixedDelay(new MyTask(), 0, 1, TimeUnit.HOURS);
Run Code Online (Sandbox Code Playgroud)
有什么建议重复我的任务,无论我什么时候运行程序?
此致,伊姆兰
kri*_*arp 15
我也建议使用Quartz.但是上面的代码可以使用initialDelay参数在一小时开始时首先运行.
Calendar calendar = Calendar.getInstance();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new MyTask(), millisToNextHour(calendar), 60*60*1000, TimeUnit.MILLISECONDS);
private static long millisToNextHour(Calendar calendar) {
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
int millis = calendar.get(Calendar.MILLISECOND);
int minutesToNextHour = 60 - minutes;
int secondsToNextHour = 60 - seconds;
int millisToNextHour = 1000 - millis;
return minutesToNextHour*60*1000 + secondsToNextHour*1000 + millisToNextHour;
}
Run Code Online (Sandbox Code Playgroud)
millisToNextHourkrishnakumarp的答案中的方法可以在Java 8中更紧凑和简单,这将导致以下代码:
public void schedule() {
ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
scheduledExecutor.scheduleAtFixedRate(new MyTask(), millisToNextHour(), 60*60*1000, TimeUnit.MILLISECONDS);
}
private long millisToNextHour() {
LocalDateTime nextHour = LocalDateTime.now().plusHours(1).truncatedTo(ChronoUnit.HOURS);
return LocalDateTime.now().until(nextHour, ChronoUnit.MILLIS);
}
Run Code Online (Sandbox Code Playgroud)
如果您能够负担得起使用外部库,那么Quartz提供了非常灵活且易于使用的调度模式.例如,cron模式应该适合您的情况.下面是一个简单的例子,它安排每小时执行某个Job:
quartzScheduler.scheduleJob(
myJob, newTrigger().withIdentity("myJob", "group")
.withSchedule(cronSchedule("0 * * * * ?")).build());
Run Code Online (Sandbox Code Playgroud)
看看教程和示例,找出适合您口味的配方.他们还展示了如何处理错误.