ScheduledExecutorService Source Code Analysis
Overview
- 本质是ExecutorService, 但它可在初始化时候指定参数来控制:1. 创建后多久被执行;2.第一次执行后每隔多久多久执行一次。
- 该接口下的schedule方法都会创建一个task, 该task可以设置需要的delay时间,该创建出来的task可以进行cancel or checkExecution. 其中方法:scheduleAtFixedRate 和 scheduleWithFixedDelay都会在创建task后periodically去执行,除非该task被cancel(eg: host reboot or deployment).
- 调用时,如果调用command用的是 Executor.execute(Runnable) and ExecutorService submit methods, 则代表没有任何delay的执行task. 0和负数的delay设置都按照立即执行task进行。
- 所有的schedule方法,都接受两个参数:第一次被执行的delay时间和第一次之后后续每隔多久执行一次task. 这两个参数被称作:relative delays and periods.
- 是否可以指定一个absolute timer or date? 格式上讲是可以的,比如: you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS), 但是在真正执行时候由于各种原因(eg: network time synchronization protocols, clock drift, etc), 其delay时间不能和你在前面的公式中date.getTime中指定的一致。
Code Analysis
- 这个接口有4个方法, 两个schedule方法;一个 scheduleAtFixedRate; 一个scheduleWithFixedDelay。
- 第一个schedule方法,返回ScheduledFuture<?>,是执行一个一次性的task(one-shot task). 执行结束便完成。
- public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
- Returns: a ScheduledFuture representing pending completion of the task and whose get() method will return null upon completion. 也就是说当可以通过检测task是否执行完成(ScheduledFuture.get() == null),然后可以自定义一些business logic or something like that, 反正是用户自定义的一些行为都可以。
- 第二个schedule方法,返回ScheduledFuture
- public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit);
- Returns: 返回一个ScheduledFuture,可以从其中获取result or cancel.
- 第三个scheduleAtFixedRate方法
- 如果中间有task执行时间超时,那么下一个execution may start late, 但是绝对不会并发执行。
- 参数period: 是指两个successive execution之间的时间。
- Return结果:调用其isDone()方法时会返回true.
- public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
- 第四个scheduleWithFixedDelay方法
- 参数delay: 前一个execution完成时间到下一个execution开始时间的间隔
- Return结果:调用其isDone()方法时会返回true.
- public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
- 第一个schedule方法,返回ScheduledFuture<?>,是执行一个一次性的task(one-shot task). 执行结束便完成。