导入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!--核心包--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
准备工作类
public class HelloJob implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { //获得JobDetail对象 JobDetail jobDetail = context.getJobDetail(); JobKey key = jobDetail.getKey(); //获取标识 System.out.println(key.getName()); System.out.println(key.getGroup()); System.out.println("当前时间:"+new Date()); } }
配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Spring 整合Quartz 进行配置遵循下面的步骤 1:定义工作任务的job 2:定义触发器Trigger,并将触发器与工作任务绑定 3:定义调度器,并将Trigger注册到Scheduler --> <!--1:定义任务的bean--> <bean name="lxJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"> <!--指定job的名称--> <property name="name" value="job"/> <!--指定job的分组--> <property name="group" value="job_group1"/> <!--指定具体的job类--> <property name="jobClass" value="com.cc.HelloJob"/> </bean> <!--2:定义触发器的bean,定义一个Cron的Trigger,一个触发器只能和一个任务绑定--> <bean id="cronTriger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <!--指定Trigger的名称--> <property name="name" value="trigger1"/> <!--指定Trigger的名称--> <property name="group" value="trigger_group1"/> <!--指定Trigger绑定的JobDetail--> <property name="jobDetail" ref="lxJob"/> <!--指定Cron表达式--> <property name="cronExpression" value="*/2 * * * * ?"/> </bean> <!--3:定义调度器,并将Trigger注册到调度器中--> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTriger"/> </list> </property> <!--添加quartz 配置--> <property name="quartzProperties"> <value> # 指定调度器名称,实际类型为:QuartzScheduler org.quartz.scheduler.instanceName = MyScheduler # 指定线程池 org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool # 线程池线程数量 org.quartz.threadPool.threadCount = 11 # 优先级 org.quartz.threadPool.threadPriority = 5 # 不持久化job org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore </value> </property> </bean> </beans>
启动类
public class TestQuartzSpring { public static void main(String[] args) { //工厂启动,调度器启动,任务调度开始 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); } }