spring定时任务配置与使用(不支持动态修改执行时间)

来源:互联网 发布:mac怎么制作铃声 编辑:程序博客网 时间:2024/05/16 10:40

1.在spring配置文件头中加入

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

2.在spring配置文件 xsi:schemaLocation=中添加:

http://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.1.xsd"

3.配置如下

<!-- spring定时任务配置 --><task:annotation-driven/><context:annotation-config/><bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<!-- 自动注入配置--->
<context:component-scan base-package="com.visionet.project.app"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /><context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /></context:component-scan>

4.保存上边代码 ,确保文件不报错 ,java代码如下:

import org.springframework.context.annotation.Lazy;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Component//必须有@Lazy(false)public class Mytask {@Scheduled(cron = "0/5 * *  * * ? ") // 每5秒执行一次public void myTest() {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触发 


1 0
原创粉丝点击