Springboot 内置定时器的使用

匿名 (未验证) 提交于 2019-12-02 23:32:01

定时器又叫定时任务、计划任务,在项目开发中使用比较普遍,它能够定时执行规定的任务,例如:订单到期处理、会员到期处理、数据报表生成等

1.启用定时任务功能

@SpringBootApplication @EnableScheduling @MapperScan("main.blog.mapper")  public class BootApplication {      public static void main(String[] args) {         SpringApplication.run(BootApplication.class, args);     } }

2.使用@Scheduled注解执行定时任务

/** * 每隔5秒执行一次 * @param model  * @return string */ @Scheduled(fixedRate = 5000) public void testTasks()  {     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:mm:dd HH:mm:ss");     System.out.println("定时任务执行时间:" + dateFormat.format(new Date())); }

3.多线程定时任务的使用

@Configuration @EnableScheduling  //开启定时器 public class SchedulerConfig implements SchedulingConfigurer {      @Override     public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {         //多线程配置         scheduledTaskRegistrar.setScheduler(taskExecutor());     }      @Bean     public Executor taskExecutor() {         return Executors.newScheduledThreadPool(100);     } }
然后再用@Scheduled执行任务时,就已经是多线程任务啦。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!