1.定时执行代码
/**
* 刷新定时任务时间信息
*/
@RestController
@Slf4j
public class RefreshCronController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture<?> future;
@Autowired
private WuhanHospitalCallJob wuhanHospitalCallJob;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
/**
* 停止定时任务
*/
private void stopCron() {
if (future != null) {
future.cancel(true);
}
log.info("DynamicTask.stopCron()");
}
/**
* 手动刷新 定时任务配置
* @param cron
*/
@GetMapping("/refreshCron")
public void refreshCron(String cron){
log.info("刷新的定时时间 refreshCron:"+cron);
String redisCron = stringRedisTemplate.opsForValue().get(DataInit.WUHAN_CRON_REDIS_KEY);
if(StringUtils.isNotBlank(redisCron)&&StringUtils.isNotBlank(cron)&&!redisCron.equals(cron)){
stringRedisTemplate.opsForValue().set(DataInit.WUHAN_CRON_REDIS_KEY,cron);
stopCron();// 先停止,在开启.
future = threadPoolTaskScheduler.schedule(new Runnable() {
@Override
public void run() {
//定时执行的任务
wuhanHospitalCallJob.wuhanOutCallJob();
}
}, new CronTrigger(cron));
}
}
/**
* 获取当前定时配置信息
* @return
*/
@GetMapping("/getCron")
public String getCron(){
return stringRedisTemplate.opsForValue().get(DataInit.WUHAN_CRON_REDIS_KEY);
}
}
2.调用方式:localhost:8080/refreshCron?cron=0 0 10 * * ?
更改定时任务,cron具体见http://cron.qqe2.com/ cron生成工具