关于定时任务的xml,一定要单独创建(里面就放标红的部分和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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<!-- 设置定时任务 -->
<task:annotation-driven/>
<context:component-scan base-package="com.jsdc.logistics.offsupply.task"></context:component-scan>
</beans>
在项目中需要添加一个定时任务,完成每天晚上访问第三方接口用于同步数据,在实际中这样的定时任务需求很多,比如系统日志,备份等等,特在网上找了相关内容。
此处使用的是SSM框架,SpringMVC的配置文件都在springmvc.xml中。
1. 在springmvc.xml添加如下内容
在xmlns中添加
xmlns:task="http://www.springframework.org/schema/task"
1
在xsi中添加
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
1
2
在中间添加
<!-- 设置定时任务 -->
<task:annotation-driven/>
1
2
新建TimerTask类
代码如下:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
*
* 类名称:TimerTask
* 类描述:定时器任务
* 创建人:geekfly
* 创建时间:Aug 29, 2016 10:56:27 AM
* @version V1.0
*
*/
@Component
public class TimerTask {
/**
* 每天22点30启动任务
*/
@Scheduled(cron = "0 30 22 ? * *")
public void test1()
{
System.out.println("job1 开始执行..."+TimeUtils.getTime());
}
@Scheduled(cron = "0/5 * * * * ?")//每隔5秒隔行一次
public void test2()
{
System.out.println("job2 开始执行");
}
}
关于cron的配置
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触发
---------------------
作者:geekfly
来源:CSDN
原文:https://blog.csdn.net/tmaskboy/article/details/52355678
版权声明:本文为博主原创文章,转载请附上博文链接!