spring定時任務

需求 : 服務器啓動後開始定時任務而且能夠註解其餘依賴的相關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上查看代碼片派生到個人代碼片

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns:task="http://www.springframework.org/schema/task"  
  3.     xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6. http://www.springframework.org/schema/beans  
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8. http://www.springframework.org/schema/context  
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10. http://www.springframework.org/schema/task  
  11. http://www.springframework.org/schema/task/spring-task-3.1.xsd">  
  12.   
  13.     <!-- 指定相應的包 -->  
  14.     <context:component-scan base-package="scheduleTest"/>  
  15.     <!-- 指定相應的類 -->  
  16.     <bean id="scheTest1" class="scheduleTest.ScheduleTest1"/>  
  17.   
  18.      <!-- 指定要定時任務須要執行的業務邏輯的java類和方法 -->  
  19.     <bean id="scheTest11" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">   
  20.         <property name="targetObject"> <ref local="scheTest1" /> </property>   
  21.             <property name="targetMethod">  
  22.             <!--  要執行的方法名稱  -->  
  23.             <value>schTest1</value>   
  24.         </property>   
  25.         <property name="concurrent" value="true" />   
  26.     </bean>  
  27.   
  28.     <!--定義觸發的時間 -->  
  29.     <bean id="scheTest1Cron" class="org.springframework.scheduling.quartz.CronTriggerBean">   
  30.         <property name="jobDetail">  
  31.             <ref bean="scheTest11" />   
  32.         </property>   
  33.         <property name="cronExpression">   
  34.             <value>0/5 * * * * ?</value>   
  35.         </property>   
  36.     </bean>  
  37.   
  38.     <!--觸發器 -->  
  39.     <bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">   
  40.         <property name="triggers">  
  41.            <list> <ref local="scheTest1Cron" /> </list>   
  42.         </property>   
  43.     </bean>  
  44.   
  45. </beans>  
相關文章
相關標籤/搜索