[英]Java Spring do scheduled task at a specific time of specific timezone
[英]Java stop scheduled task if it takes more than a specific time
我有一个计划的作业,每100秒运行一次。 有时执行此方法会花费很多时间(可以,并且没有问题)。 在这种情况下,运行方法的结果对我而言并不重要,我想将作业重新安排为下一个100秒。
在特定时间后强制正在运行的作业终止( return
)的最佳方法是什么?
我的预定代码如下:
@Scheduled(fixedDelay = 100*1000)
fun calculateLastDaysStatistics() {
logger.info("affiliate statistics thread Started Successfully")
val processStartDate = Date()
for (i in 1..prevDaysToConsider) {
logger.info("AdZone-Stats prev days $i")
val yesterday = DateUtility.addDay(Date(), -i)
val startDate = DateUtility.getZeroDayTime(yesterday.time)
val endDate = DateUtility.addDay(startDate, 1)
/* This method is probable to take a lot of time */
calculateStatistics(startDate, endDate)
}
val processLength = (Date().time - processStartDate.time) / 1000
logger.info("affiliate statistics thread finished in " + processLength + "s")
}
谢谢。
尝试使用固定速率而不是固定延迟
这是Paraschiv.E的文章。 Spring中的@Scheduled注释。 从https://www.baeldung.com/spring-scheduled-tasks引用
以固定的速率安排任务
@Scheduled(fixedRate = 1000)public void scheduleFixedRateTask(){System.out.println(“ Fixed rate task-” + System.currentTimeMillis()/ 1000); }
请注意, 任务执行的开始不等待上一个执行的完成 。
当任务的每次执行独立时,应使用此选项。
您可以使用org.springframework.scheduling.TaskScheduler
而不是基于注释的方法来实现自定义任务计划程序。
private final TaskScheduler scheduler;
@Autowired
public SchedulingManager(TaskScheduler scheduler) {
this.scheduler = scheduler;
}
在这种情况下,
ScheduledFuture scheduledeFuture = scheduler.schedule(()->{
....You job goes here..
}, new CronTrigger("*/100 * * * * *"));
您可以跟踪预定的将来,以确保它运行了预期的最大时间。
scheduledeFuture.get(100,TimeUnit.SECONDS)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.