您的位置:首页 > 编程语言 > Java开发

Spring中使用Schedule调度

2016-05-13 16:54 381 查看
  在spring中两种办法使用调度,以下使用是在spring4.0中。

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

  

<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="businessObject" />
<property name="targetMethod" value="invoke" />
<property name="concurrent" value="false" />
</bean>
<bean id="Jobtrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail" />
<property name="startDelay" value="10000" />
<property name="repeatInterval" value="3000" />
</bean>
<bean id="businessObject" class="com.aoshi.web.framework.im.polling.AutoSchedule"/>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="Jobtrigger"/>
</list>
</property>
</bean>


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

  

public class BusinessObject {

int count=0;
public void invoke(){
System.out.println(getClass().getName()+"被调用了。。。"+(count++)+"次。");

}
}


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

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

   二、基于spring注解实现调度

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

  <task:annotation-driven/>


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

  

@Component
public class AutoSchedule {

private int count=0;

@Scheduled(fixedDelay=5000)
public void invoke(){
System.out.println("被调用了:"+count++);
}
}


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

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

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

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

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

  

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


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

  

<util:properties id="applicationProps" location="application.properties" />
<context:property-placeholder properties-ref="applicationProps" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: