不過在實際的工作中,很少會直接用到它。通常都是用的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