注解使用

定时任务使用。

先在springboot入口类添加注释: EnableScheduling

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class GirlApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(GirlApplication.class, args);
  6. }
  7. }

再在定时类上添加注解,感谢网友提供的可视化Cron表达式生成器

  1. @Component
  2. public class printScheduler {
  3. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  4. @Scheduled(cron="0/5 * * * * ?")
  5. public void scheduleCheck() {
  6. logger.info("每5秒执行一次");
  7. }
  8. }

自定义使用

参考:https://www.jianshu.com/p/deede3837293

  1. package com.jege.spring.boot.task;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.scheduling.Trigger;
  6. import org.springframework.scheduling.TriggerContext;
  7. import org.springframework.scheduling.annotation.SchedulingConfigurer;
  8. import org.springframework.scheduling.config.ScheduledTaskRegistrar;
  9. import org.springframework.scheduling.support.CronTrigger;
  10. import org.springframework.stereotype.Component;
  11. import com.jege.spring.boot.data.jpa.entity.User;
  12. import com.jege.spring.boot.data.jpa.repository.UserRepository;
  13. /**
  14. * @author JE哥
  15. * @email 1272434821@qq.com
  16. * @description:动态修改定时任务cron参数
  17. */
  18. @Component
  19. public class DynamicScheduledTask implements SchedulingConfigurer {
  20. private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
  21. private static final String DEFAULT_CRON = "0/5 * * * * ?";
  22. private String cron = DEFAULT_CRON;
  23. @Autowired
  24. private UserRepository userRepository;
  25. @Override
  26. public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  27. taskRegistrar.addTriggerTask(new Runnable() {
  28. @Override
  29. public void run() {
  30. if (!cron.equals(DEFAULT_CRON)) {
  31. User user = new User("je_ge", 20);
  32. userRepository.save(user);
  33. }
  34. // 定时任务的业务逻辑
  35. System.out.println("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
  36. }
  37. }, new Trigger() {
  38. @Override
  39. public Date nextExecutionTime(TriggerContext triggerContext) {
  40. // 定时任务触发,可修改定时任务的执行周期
  41. CronTrigger trigger = new CronTrigger(cron);
  42. Date nextExecDate = trigger.nextExecutionTime(triggerContext);
  43. return nextExecDate;
  44. }
  45. });
  46. }
  47. public void setCron(String cron) {
  48. this.cron = cron;
  49. }
  50. }

启动类

  1. @EnableScheduling

修改

  1. @Autowired
  2. DynamicScheduledTask dynamicScheduledTask;
  3. // 更新动态任务时间
  4. @RequestMapping("/updateDynamicScheduledTask")
  5. @ResponseBody
  6. public AjaxResult updateDynamicScheduledTask() {
  7. dynamicScheduledTask.setCron("0/10 * * * * ?");
  8. return new AjaxResult().success();
  9. }