spring中带了对定时任务的实现,从而使你不必写一个自己的线程来定期扫描是否需要执行某任务。
具体的配置如下
spring配置文件中的配置
<!-- 定时任务 开始--> <bean name="quartzSchedualr" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger"></ref> </list> </property> <property name="configLocation" value="classpath:quartz.properties"/> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="autoOpenServer"/> <!--every day 08:00:00 execute once(0 0 8 * * ?), format: second minute hour date month weekday year(optional)--> <property name="cronExpression" value="0 49 15 * * ?"/> <!--15:49:00执行--> </bean> <bean id="autoOpenServer" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!--实际调用类--> <property name="targetObject" ref="server"/> <!--实际调用的方法--> <property name="targetMethod" value="getTime"/> </bean> <bean id="server" class="com.liu.controller.Server" /> <!--定时任务结束 -->
定时任务调用的JAVA类
package com.liu.controller;
import java.util.Date;
public class Server {
public void getTime(){
System.out.println(new Date());
}
}
对于下面这个参数的设定
<property name="cronExpression" value="0 49 15 * * ?"/> <!--15:49:00执行-->
一个Quartz的CronTrigger表达式分为七项子表达式,其中每一项以空格隔开,从左到右分别是:秒,分,时,月的某天,月,星期的某天,年;其中年不是必须的,也就是说任何一个表达式最少需要六项!
注:发现少上传了一个quartz.properties的配置文件,配置文件放到src目录下
#============================================================================
# \u914d\u7f6e Main Scheduler Properties
#============================================================================
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
#============================================================================
# \u914d\u7f6e\u6267\u884c\u7ebf\u7a0b\u6c60
#============================================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
#============================================================================
# \u914d\u7f6e JobStore
#============================================================================
org.quartz.jobStore.misfireThreshold = 60000
#\u5185\u5b58\u4e2dJobStore, \u670d\u52a1\u5668\u91cd\u542f\u65f6\u6267\u884c\u8bb0\u5f55\u4f1a\u4e22\u5931
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
#\u6570\u636e\u5e93\u4e2dJobStore\uff0c\u4e0d\u8fc7HSQLDB\u4e0d\u652f\u6301select * from locks for update \u7684\u8bed\u6cd5
#org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.HSQLDBDelegate
#org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.oracle.OracleDelegate