importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; importorg.springframework.scheduling.support.CronTrigger; importorg.springframework.stereotype.Service; importjava.util.concurrent.ScheduledFuture; publicclassManualScheduledTaskService { privateThreadPoolTaskSchedulerscheduler; privateRunnabletask; privateScheduledFuture<?>taskFuture; publicManualScheduledTaskService(ThreadPoolTaskSchedulerscheduler) { this.scheduler=scheduler; this.task= () ->System.out.println("定时任务执行:"+System.currentTimeMillis()); } publicvoidstartTask(StringcronExpression) { if (taskFuture==null||taskFuture.isCancelled()) { taskFuture=scheduler.schedule(task, newCronTrigger(cronExpression)); } } publicvoidstopTask() { if (taskFuture!=null) { taskFuture.cancel(true); } } publicbooleanisTaskRunning() { returntaskFuture!=null&&!taskFuture.isCancelled(); } }
importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.PostMapping; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.RestController; publicclassManualScheduledTaskController { privateManualScheduledTaskServicescheduledTaskService; publicManualScheduledTaskController(ManualScheduledTaskServicescheduledTaskService) { this.scheduledTaskService=scheduledTaskService; } "/startTask") (publicStringstartTask( ("cronExpression") StringcronExpression) { scheduledTaskService.startTask(cronExpression); return"定时任务已开始,cron表达式:"+cronExpression; } "/stopTask") (publicStringstopTask() { scheduledTaskService.stopTask(); return"定时任务已停止"; } "/isTaskRunning") (publicbooleanisTaskRunning() { returnscheduledTaskService.isTaskRunning(); } }
POSTMAN中调用http://localhost:port/**/startTask接口,比如POST cronExpression=*/5 * * * * *,可以在控制台看到输出,每隔5秒输出任务描述,调用http://localhost:port/**/stopTask,可以看到控制台输出停止。这就是web上手动启动和暂停任务的原理,结合业务需求,维护一下任务的id和状态到数据库里,就可以实现自己定制化的任务管理功能了。CronTrigger可以换成PeriodicTrigger也实现固定周期的定时任务。