前言
Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。—by W3Cschool
Quartz 官方文档
开始入门
首先我们要从Maven中引入spring-boot-starter-quartz
1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
|
springboot配置,可选,配置项可去官方文档查看
1 2 3 4 5
| spring.quartz.job-store-type=memory spring.quartz.auto-startup=true spring.quartz.overwrite-existing-jobs=true spring.quartz.wait-for-jobs-to-complete-on-shutdown=true
|
然后新建个quartz配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Configuration public class QuartzConfig { @Bean public JobDetail jobDetail_1() { return JobBuilder.newJob(TestJob.class) //被执行的类 .withIdentity("jobDetail_1") .storeDurably().build(); }
@Bean public Trigger myTrigger() { return TriggerBuilder.newTrigger() .forJob("jobDetail_1") .withIdentity("myTrigger") .startNow() .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * 1 * ? *")) .build(); } }
|
最后写个被执行的方法即可, 改类继承QuartzJobBean并且要实现executeInternal方法,在executeInternal方法里编写调度逻辑
1 2 3 4 5 6 7 8 9 10 11
| @Service @Async public class TestJob extends QuartzJobBean { private final Logger logger = LoggerFactory.getLogger(TestJob.class); private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override protected void executeInternal(JobExecutionContext context) { logger.info("定时器执行:" + sdf.format(new Date())); } }
|
踩坑说明
如果上面方法都编写完毕并且运行起来,但是任务没有被执行,控制台也没有报错的这种情况下多半是配置文件没有生效,我这边的情况是配置类并没有被springboot扫描到,所以我的解决方案如下:
1 2 3 4 5 6 7 8
| @EnableAsync @EnableScheduling @SpringBootApplication(scanBasePackages = "com.jwss") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
|
主要是加上了这个,让它扫描到我项目所有的代码
scanBasePackages = “com.jwss”