定时任务很简单,就是设置某个时间点,或者是每隔一段时间执行的任务。
我是通过spring注解来配置的,下面记录下配置过程:
首先要做的是添加命名空间及描述:
xmlns:task="http://www.springframework.org/schema/task" <!-- 这个放在xmlns后面 -->
<!-- 下面这两个加到 xsi:schemaLocation 里 -->
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
然后启用注解:
<!-- 启用注解 -->
<context:annotation-config/>
<context:component-scan base-package="com"/> <!-- 自动扫描com开头的包的注解-->
<aop:aspectj-autoproxy/> <!-- 切面编程,自动搜找-->
<task:annotation-driven/> <!-- 开启定时器注解 -->
其他application.xml就和以前的一样,这样配置之后就能使用注解来声明一个定时器任务了。
然后创建定时器类:
新建一个包:com.erongdu.shopping.timer
在底下创建一个类:CountOrdersJob.java
package com.erongdu.shopping.timer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class CountOrdersJob {
@Scheduled(cron="*/50 * * * * ?" )
public void doCountOrders(){
System.out.println("这里是具体执行的函数体");
}
}
这是简单的框架,我自己的定时任务太乱就不贴出来了,我提下注意点,
1.类体上要打上@Component标注,声明是spring的组件
2.在具体的定时任务方法上打上@Scheduled
3.@Scheduled的属性(自己可以在标注后面按 alt+/ 弹出提示):
cron:指定cron表达式
fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。
fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒
4.cron表达式:http://jason.hahuachou.com/
http://www.cnblogs.com/sunjie9606/archive/2012/03/15/2397626.html