1. 触发机制
定时任务的触发机制一般可分为两种,分别是按固定周期运行和在指定时间点运行。
2. 依赖 jar
commons-logging-1.1.1.jar
spring-beans-3.2.3.RELEASE.jar
spring-context-3.2.3.RELEASE.jar
spring-core-3.2.3.RELEASE.jar
spring-expression-3.2.3.RELEASE.jar
# download url
http://www.springsource.org/download/community
https://dist.apache.org/repos/dist/release/commons/logging/binaries/
3. 一个 Java 类
- package org.demo.task;
- import java.util.Date;
- public class HeartBeatTask
- {
- /**
- * 检测心跳
- */
- public void run()
- {
- String time = new Date().toString();
- System.out.println("[" + time + "] alive.");
- }
- }
4. Spring 配置文件 src/spring-tasks.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/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-3.2.xsd" >
- <!-- bean definition -->
- <bean id="heartBeat" class="org.demo.task.HeartBeatTask" />
- <!-- task definition -->
- <task:scheduler id="myScheduler" pool-size="10" />
- <task:scheduled-tasks scheduler="myScheduler">
- <task:scheduled ref="heartBeat" method="run" initial-delay="10000" fixed-delay="5000" />
- </task:scheduled-tasks>
- </beans>
# <task:scheduled> 的参数说明如下:
initial-delay : 表示第一次运行前需要延迟的时间,单位是毫秒
fixed-delay : 表示从上一个任务完成到下一个任务开始的间隔, 单位是毫秒
fixed-rate : 表示从上一个任务开始到下一个任务开始的间隔, 单位是毫秒
cron : cron 表达式,由6个字段组成,依次为 second, minute, hour, day, month, weekday 例如:
"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight
5. 一个测试类
- public static void main(String[] args)
- {
- AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring-tasks.xml");
- System.out.println("context is " + ctx);
- }