Spring中自动任务的实现

来源:互联网 发布:知乎三国和战国 编辑:程序博客网 时间:2024/06/05 10:12

使用Spring中的@Scheduled注解执行定时任务

(1) Spring配置文件applicationContext.xml中的配置

xmlns配置

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation配置

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
task注解

<task:annotation-driven/>
(2) 业务逻辑类

import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Component("test")public class TaskTest {    // 使用cron表达式定义任务执行时间    @Scheduled(cron = "0 5 0,12 * * ?")    public void test() {        // 业务逻辑    }}

Cron表达式
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式: 
Seconds Minutes Hours DayofMonth Month DayofWeek Year或 
Seconds Minutes Hours DayofMonth Month DayofWeek

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] 使用Spring @Scheduled注解执行定时任务
[2] cron表达式详解
[3] 在线Cron表达式生成器

0 0