Spring 定时器
来源:互联网 发布:python 算法包 编辑:程序博客网 时间:2024/06/04 01:37
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:
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元素:
<
task:scheduler
id
=
"myScheduler"
pool-size
=
"10"
/>
<
task:annotation-driven
scheduler
=
"myScheduler"
/>
XML配置实现方式(work方法的@scheduled标注可以去掉):
fixed-delay方式
<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 表达式方式
<
task:scheduled-tasks
>
<
task:scheduled
ref
=
"myTask"
method
=
"work"
cron
=
"3/10 * * * * ?"
/>
</
task:scheduled-tasks
>
异步作业调度:
在干活的函数上加@Async标注
@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
- spring定时器
- Spring定时器
- Spring 定时器
- Spring定时器
- spring定时器
- Spring定时器
- spring 定时器
- Spring定时器
- spring定时器
- Spring定时器
- spring 定时器
- spring 定时器
- spring 定时器
- Spring定时器
- spring定时器
- spring 定时器
- spring 定时器
- spring定时器
- CSS权重
- 欢欢的成长历程:安卓篇1(your project contains error)
- Linux下Tomcat的启动、关闭、杀死进程
- emacs lisp
- Android studio开发NDK,第一个NDK程序教程
- Spring 定时器
- 学习 note
- 加密
- php编译安装configure 一些参数详解
- 东南大学CTF之纯色
- LeetCode | House Robber
- jQuery队列控制方法详解queue()/dequeue()/clearQueue()
- NSUserDefaults 简介,使用 NSUserDefaults 存储自定义对象
- iOS下使用SHA1WithRSA算法加签源码