【JAVA】通过注解实现定时任务

来源:互联网 发布:网上兼职淘宝刷好评 编辑:程序博客网 时间:2024/05/18 02:23

首先需要在spring配置文件中配置如下内容

1.在beans中添加命名空间以及描述,如下

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" 在xsi:schemaLocation中添加如下内容:http://www.springframework.org/schema/tas  http://www.springframework.org/schema/task/spring-task-3.1.xsd  


2.在配置文件中添加具体任务,如下

<task:annotation-driven scheduler="myScheduler"/> <task:scheduler id="myScheduler" pool-size="5"/> <context:annotation-config/>  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>      <!-- scan the package and the sub package --><context:component-scan base-package="com.topic.controller"/>

3.需要导入jar包,aopalliance.jar,不然会报aop初始化错误。


接下来是java代码实现

package com.topic.controller;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class TestTimer {/**       * 启动时执行一次,之后每隔2秒执行一次       */        @Scheduled(fixedRate = 1000*2)       public void job1(){          System.out.println("启动时执行一次,之后每隔2秒执行一次  ");      }          @Scheduled(cron = "0 0 3 * * ?")      public void job2() {          System.out.println("任务进行中。。。");      }  }



附录:

cronExpression的配置说明,具体使用以及参数请百度google

字段   允许值   允许的特殊字符

秒    0-59    , - * /

分    0-59    , - * /

小时    0-23    , - * /

日期    1-31    , - * ? / L W C

月份    1-12 或者 JAN-DEC    , - * /

星期    1-7 或者 SUN-SAT    , - * ? / L C #

年(可选)    留空, 1970-2099    , - * / 

- 区间  

* 通配符  

? 你不想设置那个字段

下面只例出几个式子

 

CRON表达式    含义 

"0 0 12 * * ?"    每天中午十二点触发 

"0 15 10 ? * *"    每天早上10:15触发 

"0 15 10 * * ?"    每天早上10:15触发 

"0 15 10 * * ? *"    每天早上10:15触发 

"0 15 10 * * ? 2005"    2005年的每天早上10:15触发 

"0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发 

"0 0/5 14 * * ?"    每天从下午2点开始到2:55分结束每5分钟一次触发 

"0 0/5 14,18 * * ?"    每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 

"0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发 

"0 10,44 14 ? 3 WED"    三月的每周三的14:10和14:44触发 

"0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10:15触发 






0 0
原创粉丝点击