Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。
Quartz 可以与 J2EE 与 J2SE 应用程序相结合也可以单独使用。
Quartz 允许程序开发人员根据时间的间隔来调度作业。
Quartz 实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。
闲言少叙,书归正传!!!!!
一、依赖导入
<!-- 定时任务 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
这两个只是定时器所需要的依赖,spring、springMVC、mabatis等你需要的依赖还需要自己去配置。
一、quartz.properties配置文件(可直接赋值拿去用)
# the job scheduler name
org.quartz.scheduler.instanceName=MyScheduler
# auto set the instance id
org.quartz.scheduler.instanceId=AUTO
# the job thread in thread pool, which means the max threads can run in the same time
org.quartz.threadPool.threadCount=1
# the thread's priority
org.quartz.threadPool.threadPriority = 5
# the job data storage is memory but not database
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
# the max delay for the task execute speed time, set 2 minutes
#org.quartz.jobStore.misfireThreshold = 120000
# auto create the parent thread
#org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
二、spring.xml配置文件中配置定时器的对象
<!-- 定义一个任务类 -->
<bean id="MyJob" class="com.offcn.quartz.MyJob"></bean>
<!-- jobDetail -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!--ref中是自定义的类-->
<property name="targetObject" ref="MyJob"></property>
<!--value是自定义类MyJob中的方法名-->
<property name="targetMethod" value="execute"></property>
<property name="concurrent" value="false" /><!-- 作业不并发调度 -->
</bean>
<!-- 定义trigger 触发器 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="cronExpression" value="0/5 * * * * ?"></property>
</bean>
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="configLocation" value="classpath:quartz.properties" />
<property name="overwriteExistingJobs" value="true" />
<property name="autoStartup" value="true" />
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
三、MyJob类
package com.offcn.quartz;
import java.util.Date;
public class MyJob{
public void execute(){
System.out.println("测试定时器"+new Date());
}
}
四、总结
在SSM框架中使用Quartz定时器时,一定不要忘记匹配值web.xml文件,我在测试定时器功能时,因为没有配置web.xml文件,所以走了很长一段弯路,希望各位不要和我一样。