SSM---SpringMVC+Spring+Mybatis项目整合定时器Schedule(手动开启任务、手动关闭任务、设置定时时间)

╰半夏微凉° 2023-03-12 09:27 49阅读 0赞

1. 编写定时任务(在任务方法run()中使用service查询数据库),任务类需要实现Runnable接口

  1. public class SchedulerTask implements Runnable{
  2. /**
  3. * DESC : 定时任务逻辑
  4. *
  5. * */
  6. @Override
  7. public void run() {
  8. System.out.println("Schedule............");
  9. }
  10. }

2.编写开启/设置定时时间、关闭定时任务接口

  1. @Controller
  2. public class TaskController {
  3. @Autowired
  4. private ThreadPoolTaskScheduler threadPoolTaskScheduler;
  5. private ScheduledFuture<?> future;
  6. @Bean
  7. public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
  8. return new ThreadPoolTaskScheduler();
  9. }
  10. @RequestMapping(value = "/startTask.do", method = RequestMethod.POST)
  11. @ResponseBody
  12. public String startTask(String time) throws UnsupportedEncodingException {
  13. stopTask(); //先关闭之前的定时任务
  14. String cron = "*/5 * * * * ?"; //定时任务时间表达式
  15. //开启定时任务
  16. future = threadPoolTaskScheduler.schedule(new SchedulerTask(), new CronTrigger(cron));
  17. return "startTask";
  18. }
  19. @RequestMapping(value = "/stopTask.do", method = RequestMethod.POST)
  20. public String stopTask() {
  21. stopTimeTask();
  22. return "stopTask";
  23. }
  24. public void stopTimeTask() {
  25. if (future != null) {
  26. future.cancel(true);
  27. }
  28. }
  29. }

发表评论

表情:
评论列表 (有 0 条评论,49人围观)

还没有评论,来说两句吧...

相关阅读