Spring 定时器

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://stevex.blog.51cto.com/4300375/1352026/

其他资料:http://zywang.iteye.com/blog/949123

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值