定时器主要用于处理重复的工作,例如:从某个库定时抓取数据;扫描某一张表格的数据,某个字段值更新时做特定处理等。
首先需要导入maven依赖:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
接下来是xml配置文件:
<?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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<task:annotation-driven/>
<!-- 时间配置说明:cronExpression 至少要配置6或以上参数,参数中由空格间隔开,从左到右的各个
元素定义如下:
第一位: 秒(0-59)
第二位:分钟(0-59)
第三位:小时(0-23)
第四位: 天(1-31),代表月份中第几天
第五位:月份(1-12)
第六位:星期(1-7 ),代表是星期几
第七位:年份(1970-2099)
其中可以加入模糊定义字符[ - / * ? ],其中含义如下:
1.[-]: 字符被用来指定一个范围。如:“10-12”在小时域意味着“10点、11点、12点”
2.[/] 3.[*]: 字符被用来指定所有的值。如:”*“在分钟的字段域里表示“每分钟”
4.[?]: 字符只在日期域和星期域中使用 例如举例如下:
a. 每天晚上23-00点仅此触发一次 [0 0 23 * * ?]
b. 每月第一天凌晨1点仅此触发一次[0 0 1 1 * ?]
c. 在每天下午2点到下午2:55期间的每5分钟触发[ 0 0/5 14 * * ? ]
-->
</beans>
java实现定时器功能代码如下:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class JobTest{
@Scheduled(cron = "${value}")
public void execute(){
//TODO:执行的定时器逻辑代码
}
}
注解里面的value值为cron表达式,可用cron表达式自动生成工具,百度搜索cron第一条就是,链接也附上http://cron.qqe2.com/
如下为工具:根据选项设置你需要启动定时器的时间,会给出你最近5次的运行时间,把cron表达式copy到项目中就可以了!
启动项目之后到了预设的时间,就会执行定时器的execute方法!
定时器完成。