不过在实际的工作中,很少会直接用到它。通常都是用的spring-quartz组件,直接通过配置,让spring框架来自动装配
如下就是spring框架集成quartz组件,配置定时任务的方法
1. Maven依赖
1
2
3
4
5
6
7
8
9
10
|
< dependency > < groupId >org.springframework</ groupId > < artifactId >spring-context-support</ artifactId > < version >4.0.5.RELEASE</ version > </ dependency > < dependency > < groupId >org.quartz-scheduler</ groupId > < artifactId >quartz</ artifactId > < version >2.2.1</ version > </ dependency > |
其中quartz包是核心包,它负责实现定时任务;spring-context-support包中包含了spring对quartz的集成工具
2. Spring配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
< bean id = "task" class = "..." ></ bean > < bean id = "job" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" > < property name = "targetObject" ref = "task" /> < property name = "targetMethod" value = "run" /> </ bean > < bean id = "cronTrigger" class = "org.springframework.scheduling.quartz.CronTriggerFactoryBean" > < property name = "jobDetail" ref = "job" /> < property name = "cronExpression" value = "0 0 0 * * ?" /> </ bean > < bean id = "scheduler" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean" > < property name = "triggers" > < list > < ref bean = "cronTrigger" /> </ list > </ property > < property name = "autoStartup" value = "true" /> </ bean > |
spring对quartz的配置共分四步:
- 配置实际执行业务逻辑类,即普通的spring bean
- 配置JobDetail类,如上例中的MethodInvokingJobDetailFactoryBean,该工厂类需要指定执行业务逻辑的bean及调用的方法名
- 配置Trigger(任务触发)类,如上例中的CronTriggerFactoryBean,是基于cron表达式触发任务,需要指定JobDetail和cron表达式
- 配置scheduler(定时任务)类,如上例中的SchedulerFactoryBean,是将trigger注册到定时任务中,使trigger生效
以上就是对基本方法调用的任务和基于cron表达式触发的一个定时任务的例子,实际在Java Web项目中也大多采用这种模式
原文链接:http://blog.csdn.net/sadfishsc/article/details/50808027