Spring注解方式实现定时器

时间:2022-10-27 23:29:06

一、springmvc.xml中添加以下配置

  1、beans添加xmlnx:task

xmlns:task="http://www.springframework.org/schema/task" 

  2、xsi:schemaLocation中添加

http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-4.1.xsd

 

  3、核心配置

  (1)方法一:

 <context:annotation-config /> 
 <!-- spring扫描注解的配置(要扫描的包,即定时器所在包) -->
 <context:component-scan base-package="com.qiyuan.listener" /> 
   
<!-- 开启这个配置,spring才能识别@Scheduled注解 --> <task:annotation-driven scheduler="qbScheduler" mode="proxy"/> <task:scheduler id="qbScheduler" pool-size="10"/>

  说明:理论上只需要加上<task:annotation-driven />这句配置就可以了,这些参数都不是必须的(见方法二)。

  (2)方法二

<!-- task任务注解扫描包(定时器开关) -->
<task:annotation-driven/> <!-- 用定时器注解 -->
     
<!-- 扫描位置是 -->
<context:annotation-config/>  
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
<context:component-scan base-package="com.qiyuan.listener"/>  

 

二、定时任务Java代码

  (1)接口和实现类

package com.qiyuan.listener;

public interface Test {

    public void myTest1(); 
    
    public void myTest2(); 
    
    public void myTest3();
    
    public void myTest4();
    
}

 

package com.qiyuan.listener;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.qiyuan.bean.TRate;
import com.qiyuan.service.AnalysticService;
import com.qiyuan.service.CenterPurseService;
import com.qiyuan.service.OrderService;
import com.qiyuan.service.RateService;
import com.qiyuan.util.RateUtil;


@Component
public class TestImp implements Test {

    @Resource
    private RateService rateServiceImp;
    @Resource
    private CenterPurseService centerPurseServiceImp;
    @Resource
    private OrderService orderServiceImp;
    @Resource
    private AnalysticService analysticServiceImp;
    
    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    int count4 = 0;
    
    @Scheduled(cron="0 */5 * * * ?")   //每5分钟执行一次  
    @Override
    public void myTest1() {
        System.out.println("进入测试定时器1");  
        ++count1;
        System.out.println("定时器1:时间=" + new Date() + " 执行了" + count1 + "次"); // 1次
        //查询各种币的汇率
        TRate tRate=new TRate();
        tRate.setRate(1);
        tRate.setYkcrate(RateUtil.YKC());
        tRate.setBtcrate(RateUtil.BTC());
        tRate.setLtcrate(RateUtil.LTC());
        tRate.setEthrate(RateUtil.ETH());
        tRate.setLastmodify(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        System.out.println("==========汇率"+tRate);
        //更新汇率表
        rateServiceImp.updateRate(tRate);
        //查询钱包充值记录,更新用户钱包
        centerPurseServiceImp.searchPurseChargeRecord();
    }

    
    @Scheduled(cron="0 0 2 * * ?")   //每天凌晨一点执行一次  
    @Override
    public void myTest2() {
        System.out.println("进入测试定时器2");  
        ++count2;
        System.out.println("定时器2:时间=" + new Date() + " 执行了" + count2 + "次"); // 1次
        //每天凌晨1点:超过7天已发货但未收货的让系统自动收货
        orderServiceImp.autoAcceptOrder();
    }
    

    @Scheduled(cron="0 0 2 * * ?")   //每天凌晨两点执行一次  
    @Override
    public void myTest3() {
        System.out.println("进入测试定时器3");  
        ++count3;
        System.out.println("定时器3:时间=" + new Date() + " 执行了" + count3 + "次"); // 1次
        //每天凌晨1点统计前一天的数据
        analysticServiceImp.insertAnalystic();
    }
    
    
    @Scheduled(cron = "0 0 3 1 * ?")   //每个月1号凌晨三点执行一次
    public void myTest4(){
        System.out.println("进入测试定时器4");  
        ++count4;
        System.out.println("定时器3:时间=" + new Date() + " 执行了" + count4 + "次"); // 1次
        //每个月1号凌晨三点清空临时订单表的数据
        orderServiceImp.deleteAllTempOrder();
    }

}

 

三、扩展资料

  关于@Scheduled注解,查看源文件中该注解的定义

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Scheduled  
{  
  public abstract String cron();  
  
  public abstract long fixedDelay();  
  
  public abstract long fixedRate();  
}

  参数具体介绍见:

  (1)理解 Spring 定时任务的 fixedRate 和 fixedDelay 的区别

  

  (2)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task-4.1.xsd  " ><!-- 扫描:通知spring容器采用自动扫描机制查找注解的bean --><context:component-scan base-package="com.qiyuan.controller"/>
<!-- 默认加载方法,启动时加载 (定时器的另外一种方法)--><!-- <bean id="templateAnnotationInit1" class="com.qiyuan.listener.TestTimer1" init-method="showTimer1" /><bean id="templateAnnotationInit2" class="com.qiyuan.listener.TestTimer2" init-method="showTimer2" /><bean id="templateAnnotationInit3" class="com.qiyuan.listener.TestTimer3" init-method="showTimer3" /> --><!-- task任务注解扫描包(定时器开关) --><task:annotation-driven/> <!-- 用定时器注解 -->  <!-- 扫描位置是 --><context:annotation-config/>      <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>     <context:component-scan base-package="com.qiyuan.listener"/>  <!--开启springmvc 注解 --><mvc:annotation-driven>  <mvc:message-converters>           <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>       </mvc:message-converters></mvc:annotation-driven><!-- 视图解析器 --><bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">   <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>   <property name="prefix" value="/WEB-INF/jsp/"></property>   <property name="suffix" value=".jsp"></property></bean><!-- 前台拦截器 --><mvc:interceptors>     <mvc:interceptor>      <!-- 过滤全部请求 -->          <mvc:mapping path="/**"/>          <!--  除了此请求 -->          <mvc:exclude-mapping path="/login/*"/>          <mvc:exclude-mapping path="/item/*"/>          <mvc:exclude-mapping path="/analystic/*"/>          <mvc:exclude-mapping path="/members/*"/>          <mvc:exclude-mapping path="/itemMage/*"/>          <mvc:exclude-mapping path="/back_order/*"/>          <mvc:exclude-mapping path="/back_order1/*"/>          <mvc:exclude-mapping path="/logistics/*"/>          <mvc:exclude-mapping path="/product/*"/>          <mvc:exclude-mapping path="/admin/*"/>          <bean class="com.qiyuan.interceptor.MyHandlerInterceptor"></bean>     </mvc:interceptor></mvc:interceptors><!-- 后台(管理员)拦截器 --><mvc:interceptors>     <mvc:interceptor>      <!-- 过滤全部请求 -->          <mvc:mapping path="/**"/>          <!--  除了此请求 -->          <mvc:exclude-mapping path="/login/*"/>          <mvc:exclude-mapping path="/centerAddress/*"/>          <mvc:exclude-mapping path="/centerOrder/*"/>          <mvc:exclude-mapping path="/centerPurse/*"/>          <mvc:exclude-mapping path="/centerScore/*"/>          <mvc:exclude-mapping path="/centerTeam/*"/>          <mvc:exclude-mapping path="/item/*"/>          <mvc:exclude-mapping path="/order/*"/>          <mvc:exclude-mapping path="/shopCar/*"/>          <mvc:exclude-mapping path="/userCenter/*"/>          <mvc:exclude-mapping path="/back_order1/*"/>          <bean class="com.qiyuan.interceptor.MyHandlerInterceptor_back"></bean>     </mvc:interceptor></mvc:interceptors><!-- 后台(供应商)拦截器 --><mvc:interceptors>     <mvc:interceptor>      <!-- 过滤全部请求 -->          <mvc:mapping path="/**"/>          <!--  除了此请求 -->          <mvc:exclude-mapping path="/login/*"/>          <mvc:exclude-mapping path="/centerAddress/*"/>          <mvc:exclude-mapping path="/analystic/*"/>          <mvc:exclude-mapping path="/centerOrder/*"/>          <mvc:exclude-mapping path="/centerPurse/*"/>          <mvc:exclude-mapping path="/centerScore/*"/>          <mvc:exclude-mapping path="/centerTeam/*"/>          <mvc:exclude-mapping path="/item/*"/>          <mvc:exclude-mapping path="/order/*"/>          <mvc:exclude-mapping path="/shopCar/*"/>          <mvc:exclude-mapping path="/userCenter/*"/>          <mvc:exclude-mapping path="/admin/*"/>          <mvc:exclude-mapping path="/itemMage/*"/>          <mvc:exclude-mapping path="/logistics/*"/>          <mvc:exclude-mapping path="/members/*"/>          <mvc:exclude-mapping path="/back_order/*"/>          <mvc:exclude-mapping path="/product/*"/>          <bean class="com.qiyuan.interceptor.MyHandlerInterceptor_back1"></bean>     </mvc:interceptor></mvc:interceptors><!-- 文件上传 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   <property name="defaultEncoding" value="UTF-8"></property><property name="maxUploadSize" value="99999999999"></property><property name="resolveLazily" value="true"></property></bean>
</beans>