spring 中配置定时调度两种方法介绍

来源:互联网 发布:麦子学院python 网盘 编辑:程序博客网 时间:2024/05/17 20:14

方法一:

直接用jdk api的Timer类,无需配置spring文件

1、用@compent注解,实现InitializingBean接口 ,spirng会自动去查找afterPropertiesSet()方法,

2、在afterPropertiesSet方法中写业务实现,调用timer的schedule方法或者scheduleAtFixedRate方法

          schedule(TimerTask task,Date time)
          安排在指定的时间执行指定的任务。

          scheduleAtFixedRate(TimerTask task,Date firstTime, long period)
          安排指定的任务在指定的时间开始进行重复的固定速率执行

代码实现如下:

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import java.util.TimerTask;
import javax.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import com.cssweb.payment.account.service.support.AccountServiceSupport;

@Component
public class GetTimer implements InitializingBean{
 
 private Date date;
 
 @Override
 public void afterPropertiesSet() throws Exception {
  init();//初始化参数,每天凌晨00:00:00开始作业
  //System.out.println("时间是:============="+date);
  new Timer().schedule(test(), date);  //test()为自己要处理的业务实现方法
 }
 
 /** 
 * 初始化参数 
 *
 */
  public void init(){ 
     Calendar cal = Calendar.getInstance();
     cal.set(Calendar.HOUR_OF_DAY, 0);
     cal.set(Calendar.SECOND, 0);
     cal.set(Calendar.MINUTE, 0);
     cal.add(Calendar.DAY_OF_MONTH, 1);
     date = cal.getTime();
 }


 public static TimerTask test(){
  return new TimerTask() {
   @Override
   public void run() {
    System.out.println(new Date()+"开始了------------------------------");
   }
  };
 }


}

 

方法二:用spring配置文件进行配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
   
 <bean id="remindSchedule" class="com.checking_in_remind.controller.Remind" />   //找到对应的类名
 
 <!-- 定义调用对象和调用对象的方法(jobDetail) -->
  <bean id="remindtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  <!-- 注册定时任务执行时调用的类 -->
  <property name="targetObject" ref="remindSchedule" />
  <!-- 注册定时任务执行时调用的方法 -->
   <property name="targetMethod" value="getPersonInfo" />
  <!-- 此参数为false等于JobDetail对象实现了Stateful接口,jobs不会并发运行-->
   <property name="concurrent" value="false" />
 </bean>
 
 <bean id="remindCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail" ref="remindtask" />
  <!-- 每5分钟执行一次任务调度 -->
  <property name="cronExpression" value="0 */5 * * * ?"/>
 </bean>
</beans>

 

1 0