SpringBoot内置定时任务,只需注解@Scheduled就可以开启定时。
首先在入口程序xxxApplication 添加注解@EnableScheduling
开发时遇到的应用场景:已经发布的serviceJob,需要定时从slurm查询其运行状态(pending,running,canceled,failed等),更新到数据库中,代码如下,设定为每3秒更新一次
@Scheduled(cron = "*/3 * * * * *")
public void updateJobStatusScheduledTask() throws JsonProcessingException {
List<JobStatus> jobStatuses = JobStatus.needUpdate();
List<ServiceJob> serviceJobs = serviceJobDAO.findByJobStatusIsIn(jobStatuses);
if(serviceJobs != null){
System.out.println("更新serviceJob状态");
for (ServiceJob serviceJob : serviceJobs) {
System.out.println("当前更新serviceJobKey:" + serviceJob.getJobKey());
String jobKey = serviceJob.getJobKey();
updateServiceJobStatusAndEnv(jobKey);
}
}
}
参考链接: