1、下载依赖包
"org.quartz-scheduler:quartz:2.2.3",
"org.quartz-scheduler:quartz-jobs:2.2.3",
2、 配置quartz.properties
#主要是配置quartz参数
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.scheduler.instanceId=AUTO
org.quartz.scheduler.autoStartup=true
org.quartz.threadPool.threadCount=5
3、编写trigger、jobdetail、schedule
1)、编写trigger
/**
* 描述出发Job执行的时间触发规则
* 配置时间trigger(有一种配置cron
*http://blog.csdn.net/changlu0/article/details/53021581)
*/
@Configuration
public class Trigger {
@Bean(name = "jobTest1Trigger")
public CronTriggerFactoryBean jobTest1Trigger(@Qualifier(value = "jobTest2FactoryBean") JobDetail jobDetail,
@Value("${quartz.jobTest1Trigger.cron}") String cron) {
return cronTriggerFactoryBean(jobDetail, cron);
}
private CronTriggerFactoryBean cronTriggerFactoryBean(JobDetail jobDetail, String cron) {
CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
factoryBean.setJobDetail(jobDetail);
factoryBean.setCronExpression(cron);
return factoryBean;
}
}
2) 编写jobdetail
/**
* 顾名思义 就是配置一个调度任务
*/
@Configuration
public class JobConfig {
@Bean
public JobDetailFactoryBean jobTest1FactoryBean() {
return jobDetailFactoryBean(Jobtest1.class);
}
private JobDetailFactoryBean jobDetailFactoryBean(Class clazz){
JobDetailFactoryBean cronTriggerFactoryBean = new JobDetailFactoryBean();
cronTriggerFactoryBean.setJobClass(clazz);
cronTriggerFactoryBean.setDurability(true);
return cronTriggerFactoryBean;
}
}
3)编写schedule
/**
* 代表一个Quartz的独立运行容器,Trigger和JobDetail要注册到 Scheduler中才会生效,也就是让调度器知道有哪些触发器和任务,才能进行按规则进行调度任务
*/
@Configuration
@ConditionalOnProperty(name = "quartz.enabled")
public class ScheduleConfig {
@Bean
public SchedulerFactoryBean schedulerFactoryBean(Trigger[] trigger) throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setQuartzProperties(quartzProperties());
factory.setTriggers(trigger);
return factory;
}
private Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
}
4) 编写job
public class Jobtest1 extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("it's my job test1");
}
}
5)、配置Spring文件
quartz:
enabled: true
jobTest1Trigger:
cron: 0/5 * * * * ?
6)、 执行
我这里使用Spring启动的