Spring中使用Schedule调度

  在spring中两种办法使用调度,以下使用是在spring4.0中。

  一、基于application配置文件,配置入下:

  

 1     <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
 2         <property name="targetObject" ref="businessObject" />
 3         <property name="targetMethod" value="invoke" />
 4         <property name="concurrent" value="false" />
 5     </bean>
 6     <bean id="Jobtrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
 7         <property name="jobDetail" ref="jobDetail" />
 8         <property name="startDelay" value="10000" />
 9         <property name="repeatInterval" value="3000" />
10     </bean>
11     <bean id="businessObject" class="com.aoshi.web.framework.im.polling.AutoSchedule"/>
12     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
13         <property name="triggers">
14             <list>
15                 <ref bean="Jobtrigger"/>
16             </list>
17         </property>
18     </bean>

其中的businessObject类就是调用调度的类,代码如下:

  

1 public class BusinessObject {
2 
3     int count=0;
4     public void invoke(){
5         System.out.println(getClass().getName()+"被调用了。。。"+(count++)+"次。");
6         
7     }
8 }

以上配置中targetMethod指定了调度的方法,concurrent设置是否并发执行。触发器中 startDelay设置程序之前延迟,单位是毫秒。repeatInterval设置执行的间隔,单位是毫秒。最后配置的是调度工厂,指定触发器。

 *这种方法需要quartz.jar 和quartz-jobs.jar包的支持。 

   二、基于spring注解实现调度

   使用spring注解来驱动调度,首先需要在spring配置文件中加入task命名空间,xmlns:task="http://www.springframework.org/schema/task"。接着加入调度注解扫描配置:

  <task:annotation-driven/>

  接着是写注解的调度代码:

  

 1 @Component
 2 public class AutoSchedule {
 3 
 4     private int count=0;
 5     
 6     @Scheduled(fixedDelay=5000)
 7     public void invoke(){
 8         System.out.println("被调用了:"+count++);
 9     }
10 }

@Scheduled注解的方法就会在程序启动时候被自动执行,其中几个常配置的参数,分别是

  fixedRate: 每一次执行调度方法的间隔,可以不用等上一次方法执行结束。可以理解为并发执行的。

  fixedDely: 两次调度方法执行的间隔,它必须等上一次执行结束才会执行下一次。

  cro: 配置调度配置字符串。

其中配置字符串可以从properties文件中取得。例如:

  

1 @Scheduled(cron = "${cron.expression}")
2     public void demoServiceMethod()
3     {
4         System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());
5     }

  在spring配置文件中引用配置文件:

  

1 <util:properties id="applicationProps" location="application.properties" />
2 <context:property-placeholder properties-ref="applicationProps" />
原文地址:https://www.cnblogs.com/bigbang92/p/spring-schedule.html