首页  

Timer和ScheduledExecutorService的区别     所属分类 java 浏览量 1326
Timer特点

1 一个Timer只使用一个线程
   执行完一个 timerTask  才会执行 下一个 timerTask
   
    
2  TimerTask 抛出异常,会终止 TimerThread ,导致后续 TimerTask 不再执行


TimerTask 放到 TaskQueue
TimerThread 循环取出 nextExecutionTime 最小的 TimerTask执行


Timer TaskQueue TimerThread TimerTask

TimerTask[] queue = new TimerTask[128];

Return the "head task" of the priority queue.  (The head task is an task with the lowest nextExecutionTime.)
TimerTask getMin() {
        return queue[1];
    }


public void scheduleAtFixedRate(TimerTask task, Date firstTime,long period) 


ScheduledExecutorService
public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService
        
1 ScheduledExecutorService 可设置多个线程
2 任务抛出异常,只是中断该任务,不会影响其它任务运行


public ScheduledFuture scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);

public ScheduledFuture scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);


scheduleAtFixedRate 与 scheduleWithFixedDelay 的区别

scheduleAtFixedRate ,从 上一个任务开始时 开始计时,period时间过去后,检查上一个任务是否执行完,如果执行完,则当前任务立即执行,如果没有执行完,则等上一个任务执行完后执行。

scheduleWithFixedDelay,从 上一个任务结束时 开始计时,period时间后执行。



timer 中 任何 一个任务抛出异常 ,其他任务将不会被执行
ScheduledExecutorService 中  任务 抛出异常后终止运行 , 但不影响其他任务运行 
If any execution of the task encounters an exception, subsequent executions are suppressed.
定时任务一定要处理异常 ,譬如直接抓 Throwable 然后记录日志 ,避免抛出未处理的异常终止运行	

定时任务处理范式
try{
    ...
}catch(Throwable e){
    # log error  
    ...
}



测试代码 
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/timer/TimerTest.java

 ExecutorService中submit和execute的区别 

上一篇     下一篇
java number 比较陷阱

手机4G信号突然变成2G信号

JVM性能分析利器 JMC 和 JFR

不要在finally块中使用return

jcmd PerfCounter 说明

集合遍历删除注意点