JDK中Timer类

java.util.Timer定时器实际上是一个单线程,定时调度所拥有的TimerTask任务。

TimerTask类是一个定时任务类,实现了Runnable接口,而且是一个抽象类,需要定时执行的任务都需要重写它的run方法。

TImer类的缺陷

1)单线程,如果存在多个任务,某个任务执行时间过长,就会导致任务时间延迟。

2)异常终止,如果TimerTask抛出了未捕获的异常,则也会导致Timer线程终止,已经被安排但尚未执行的TimerTask也不会再执行了。

3)执行周期任务时依赖系统时间:如果当前系统时间发生了变化,会出现一些执行上的变化。

ScheduledExecutorServiceh和Spring Schedule

jdk1.5推出了基于线程池设计的ScheduledExecutorService,其设计思想是:每个被调度的任务都会由线程池中的一个线程去执行,因此任务是并发的,相互之间不会受到干扰。

其实除了自己可以实现定时任务,还可以通过使用Spring实现定时任务。

1.在Spring配置文件头中添加命名空间及描述(第9行、14和15行)

分布式定时任务/分布式锁
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
 8        xmlns:jaxws="http://cxf.apache.org/jaxws"       
 9        xmlns:task="http://www.springframework.org/schema/task"       
10        xsi:schemaLocation="http://www.springframework.org/schema/beans      
11        http://www.springframework.org/schema/beans/spring-beans.xsd
12        http://www.springframework.org/schema/context 
13        http://www.springframework.org/schema/context/spring-context.xsd
14        http://www.springframework.org/schema/task
15        http://www.springframework.org/schema/task/spring-task-3.0.xsd       
16        http://www.springframework.org/schema/aop 
17        http://www.springframework.org/schema/aop/spring-aop.xsd
18        http://www.springframework.org/schema/tx
19        http://www.springframework.org/schema/tx/spring-tx.xsd
20        http://www.springframework.org/schema/data/jpa 
21        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
22        http://cxf.apache.org/jaxws 
23        http://cxf.apache.org/schemas/jaxws.xsd
24        ">
View Code

相关文章:

  • 2021-08-14
  • 2021-09-23
  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
  • 2021-08-31
猜你喜欢
  • 2022-12-23
  • 2021-12-30
  • 2021-10-22
  • 2022-12-23
  • 2021-11-12
相关资源
相似解决方案