需求 : 服務器啓動後開始定時任務而且能夠註解其餘依賴的相關beanhtml
1. 註解方式 ; 2 配置文件 java
註解實現方式web
1.1 自定義類DbScheduleTask spring
@Component服務器
public class DbScheduleTask{app
@AutoWiredspa
private UserService userService;.net
@AutoWiredcode
private OrderService orderService;component
@Schedule(cron="* 0/1 * * * ?")
task(){
userService.sync();
orderService.sync();
}
}
2. 配置文件方式
一、相應的web.xml沒有什麼變化,所以便再也不羅列。一樣的,相應的java代碼業務邏輯改動也不大,只是在原來的基礎上去掉@Component和@Scheduled(cron = "0/5 * * * * ?")參數,也就是把這個類和方法變成一個最簡單的java類和方法就能夠了。
二、既然是配置文件的方式,那麼改動大的天然就是pring.xml配置,把本來用註解實現的定時功能放到配置中來,改動後的配置以下:
[html] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns:task="http://www.springframework.org/schema/task"
- xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-3.1.xsd">
-
- <!-- 指定相應的包 -->
- <context:component-scan base-package="scheduleTest"/>
- <!-- 指定相應的類 -->
- <bean id="scheTest1" class="scheduleTest.ScheduleTest1"/>
-
- <!-- 指定要定時任務須要執行的業務邏輯的java類和方法 -->
- <bean id="scheTest11" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
- <property name="targetObject"> <ref local="scheTest1" /> </property>
- <property name="targetMethod">
- <!-- 要執行的方法名稱 -->
- <value>schTest1</value>
- </property>
- <property name="concurrent" value="true" />
- </bean>
-
- <!--定義觸發的時間 -->
- <bean id="scheTest1Cron" class="org.springframework.scheduling.quartz.CronTriggerBean">
- <property name="jobDetail">
- <ref bean="scheTest11" />
- </property>
- <property name="cronExpression">
- <value>0/5 * * * * ?</value>
- </property>
- </bean>
-
- <!--觸發器 -->
- <bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="triggers">
- <list> <ref local="scheTest1Cron" /> </list>
- </property>
- </bean>
-
- </beans>