Spring 定时器
最常见的JAVA定时器有JDK自带的Timer、ScheduledThreadExecutor以及第三方的Quartz,Timer自身有很多缺陷(如不支持多线程,多任务执行时会出现任务滞后执行,没有处理运行时异常可导致定时器异常终止等),实际上已经被JDK 5 提供的ScheduledThreadExecutor替代,ScheduledThreadExecutor基本解决了Timer的缺陷,但ScheduledThreadExecutor不够强大,它不能支持像Cron Job这样复杂的调度。Quartz则是名副其实的工业标准,支持各种各样复杂的任务调度,支持JTA事务管理、支持集群等,可见Quartz很强大的同时也变得有点复杂,有点“重”。
Spring 从3开始自己提供了一个比较Quartz相对轻量的定时器框架,支持一般定时任务和Cron 表达式定义的定时任务,支持异步任务调度执行,同时提供Annotation配置方式和task XML namespace来支持定时任务的调度配置,相对Quartz配置大大简化,开发更加简单。
Annotation实现方式:
-
在具体干活的函数上加标注@Scheduled:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package
com.myco.tasks;
@Service
(
"myTask"
)
public
class
MyTask {
//A cron-like expression, extending the usual UN*X definition to include triggers on the second as well as minute, hour, day of month, month and day of week.
//@scheduled(cron)
//Execute the annotated method with a fixed period between the end of the last invocation and the start of the next.
//@scheduled(fixedDelay)
//Execute the annotated method with a fixed period between invocations.
@Scheduled
(fixedRate=
1000
)
public
void
work() {
// task execution logic
}
}
|
-
配置文件增加task:annotation-driven元素:
1
2
|
<
task:scheduler
id
=
"myScheduler"
pool-size
=
"10"
/>
<
task:annotation-driven
scheduler
=
"myScheduler"
/>
|
XML配置实现方式(work方法的@scheduled标注可以去掉):
-
fixed-delay方式
1
2
3
4
5
|
<task:scheduler id=
"myScheduler"
pool-size=
"10"
/>
<task:scheduled-tasks scheduler=
"myScheduler"
>
<task:scheduled ref=
"myTask"
method=
"work"
fixed-delay=
"10000"
/>
</task:scheduled-tasks>
|
-
Cron 表达式方式
1
2
3
|
<
task:scheduled-tasks
>
<
task:scheduled
ref
=
"myTask"
method
=
"work"
cron
=
"3/10 * * * * ?"
/>
</
task:scheduled-tasks
>
|
异步作业调度:
-
在干活的函数上加@Async标注
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Component
public
class
AsyncWorker
implements
Worker {
@Async
public
void
work(
int
i) {
String threadName = Thread.currentThread().getName();
System.out.println(
" "
+ threadName +
" beginning work on "
+ i);
try
{
Thread.sleep(
5000
);
// simulates work
}
catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(
" "
+ threadName +
" completed work on "
+ i);
}
}
|
-
配置文件中增加<task:annotation-driven />
其他资料:http://zywang.iteye.com/blog/949123