本文共 2999 字,大约阅读时间需要 9 分钟。
1.pom的引入
定时任务不需要引入特别的依赖(也可以说在springboot中已经集成到spring-boot-starter里面了)
org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-devtools true
2.配置
定时任务 只需要简单两步
举例:
(1)启动类加上注解 @EnableScheduling
@SpringBootApplication@EnableSchedulingpublic class SpringbootSchedulingApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSchedulingApplication.class, args); }}
(2)在需要执行的方法(定时任务实现类)上加上 @Scheduled(cron="*/9 * * * * ?")
@Componentpublic class SchedulerTask1 { @Scheduled(cron="*/9 * * * * ?") private void task(){ System.out.println("定时任务"); }}
@Scheduled
有两种参数设置方法,一种是 cron="*/9 * * * * ?"
,一种是 fixedRate = 9000
,都表示每隔9秒执行一次。
fixedRate 说明
@Scheduled(fixedRate = 9000)
:上一次开始执行时间点之后9秒再执行@Scheduled(fixedDelay = 9000)
:上一次执行完毕时间点之后9秒再执行@Scheduled(initialDelay=1000, fixedRate=9000)
:第一次延迟1秒后执行,之后按fixedRate的规则每9秒执行一次@Configuration@EnableSchedulingpublic class SchedulingConfigurerConfiguration implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(10); taskScheduler.setThreadNamePrefix("project-init-poolScheduler-"); taskScheduler.initialize(); taskRegistrar.setTaskScheduler(taskScheduler); }}
添加一个完整的例子:
配置:
package com.ciicgat.employeefinancial.config;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;import org.springframework.scheduling.config.ScheduledTaskRegistrar;@Configuration@EnableSchedulingpublic class SchedulingConfigurerConfiguration implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(10); taskScheduler.setThreadNamePrefix("project-init-poolScheduler-"); taskScheduler.initialize(); taskRegistrar.setTaskScheduler(taskScheduler); }}
方法:
@Servicepublic class ScheduleFactory { @Autowired ScheduleService scheduleService;
@Scheduled(fixedDelay = 60 * 1000 * 5) public void syncProductList() { scheduleService.syncProductList(); } @Scheduled(fixedDelay = 60 * 1000 * 8) public void syncProductDetails(){ scheduleService.syncProductDetails(); }}
注意:扫描注解的时候 ,需要扫描到这个service的包 (这个service的包在base-package下面)
转载地址:http://rfjxi.baihongyu.com/