本文主旨在于能定时任务能运行起来,对于背后原理尚未深入探讨,所以若提及原理相关,多是揣摩估计,并未考究,仅供参考
一、单个定时任务时
1. pom.xml
在springboot基础上加上以下依赖:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
2. 添加任务类
/**
* 一个任务
*
* @author Sprite
* @date 2018/09/06
*/
@Component
public class SingleTask {
public void singleTask(){
System.out.println("执行单个定时任务");
}
}
看到有文章说,必须要有@EnableScheduling和@Configuration贴在任务类上面,但是亲测发现去掉亦可. 大概是因为@EnableScheduling其实是springboot本身对于定时功能的支持的自动装配,与Quartz无关,后面配置已经将该任务类加上,故这里不加这个注解也可以
3.配置类
package com.xuebi.qrtz_demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
/**
* 配置
*
* @author Sprite
* @date 2018/09/06
*/
@Configuration
public class QuartzConfig {
@Bean
public MethodInvokingJobDetailFactoryBean detailFactoryBean(SingleTask task) {
MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
jobDetailFactoryBean.setConcurrent(false);
jobDetailFactoryBean.setName("printOut");
jobDetailFactoryBean.setGroup("printOut_group");
jobDetailFactoryBean.setTargetObject(task);
jobDetailFactoryBean.setTargetMethod("singleTask");
return jobDetailFactoryBean;
}
@Bean
public CronTriggerFactoryBean cronTrigger(MethodInvokingJobDetailFactoryBean detailFactoryBean) {
CronTriggerFactoryBean triggerFactoryBean = new CronTriggerFactoryBean();
triggerFactoryBean.setJobDetail(detailFactoryBean.getObject());
// 设置表达式,每3秒执行一次
triggerFactoryBean.setCronExpression("0/3 * * * * ?");
triggerFactoryBean.setName("everyThreeSeconds");
return triggerFactoryBean;
}
@Bean
public SchedulerFactoryBean schedulerFactory(CronTriggerFactoryBean cronTrigger) {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
// 设置是否任意一个已定义的Job会覆盖现在的Job。默认为false,即已定义的Job不会覆盖现有的Job。
bean.setOverwriteExistingJobs(true);
// 延时启动,应用启动10秒后,定时器才开始启动
bean.setStartupDelay(10);
// 注册定时触发器
bean.setTriggers(cronTrigger.getObject());
return bean;
}
}
控制台输出结果
控制台结果看到控制台的这个结果,就表示已经成功了
网友评论