上一篇说明了一下Spring自带的定时器设置,这一件就简单叙述一下QuartZ的配置过程。
首先是新建一个QuartZ的配置文件-quartz.properties:
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 1
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.plugin.jobInitializer.class =org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames =init/quartz_data_jobs.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
再新建一个XML文件用于存放定时执行的Job信息-quartz_data_jobs.xml:
<?xml version="1.0" encoding="UTF-8"?>
<job-scheduling-data
xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData
http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"
version="1.8">
<schedule>
<job>
<name>FirstJob</name>
<group>DummyGroup</group>
<description>This is FirstJob</description>
<job-class>com.example.demo.quartz.TestJob2</job-class>
</job>
<trigger>
<cron>
<name>dummyTrigger</name>
<job-name>FirstJob</job-name>
<job-group>DummyGroup</job-group>
<!-- It will run every 2 seconds -->
<cron-expression>0/2 * * * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>
创建需要执行的Job类-TestJob2:
package com.example.demo.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
public class TestJob2 implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("正在执行定时任务:"+new Date());
}
}
最后是创建一个配置类,用于QuartZ的启动配置-QuartZConfig:
package com.example.demo.quartz;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartZConfig {
private ApplicationContext applicationContext;
/**
* quartz 启动配置
*/
@Bean
public SchedulerFactory quartz() throws SchedulerException {
// Creating scheduler factory and scheduler
SchedulerFactory factory = new StdSchedulerFactory("quartz.properties");
Scheduler scheduler = factory.getScheduler();
scheduler.start();
return factory;
}
}
执行结果如下:
可以看到定时任务正常执行了。
补充maven引包:
<!--QuartZ定时任务-->
<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>