springboot定时任务的启停
作者:互联网
@Slf4j
@RestController
@Api(description = "定时任务")
@RequestMapping("/timer/task")
public class DynamicTaskController {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture<?> future;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
/**
* 启动定时任务
* @return String
*/
@GetMapping("/startCron")
public Result startCron() {
future = threadPoolTaskScheduler.schedule(()->{
//此处执行定时执行的程序
log.info("################################ I do timer #################");
},new Trigger(){
@Override
public Date nextExecutionTime(TriggerContext triggerContext){
// 这里可以做成配置,此处写死没5秒执行一次
return new CronTrigger("0/5 * * * * ?").nextExecutionTime(triggerContext);
}
});
log.info("################################ timer is start #################");
return ResultUtils.success();
}
/**
* 关闭定时任务
* @return String
*/
@PostMapping("/stopCron")
public Result stopCron() {
if (future != null) {
future.cancel(true);
}
log.info("################################ timer is stop #################");
return ResultUtils.success();
}
}
标签:################################,return,springboot,timer,启停,定时,future,public 来源: https://blog.csdn.net/TarkuNi/article/details/121331491