一、ScheduledThreadPoolExecutor简介
1.1、构造方法
ScheduledThreadPoolExecutor有四个构造方法,如下所示:
ScheduledThreadPoolExecutor(int corePoolSize) |
|
---|---|
ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) |
|
ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) |
|
ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) |
|
1.2、方法
decorateTask(Runnable runnable,RunnableScheduledFuture<V> task)
-
作用:修改或替换用于执行runnable的任务。
decorateTask(Callable<V> callable,RunnableScheduledFuture<V> task)
- 作用:修改或替换用于执行可调用的任务。
- 作用:执行
command
所需的延迟为零。
getContinueExistingPeriodicTasksAfterShutdownPolicy()
- 作用:获取有关是否继续执行现有定期任务的策略,即使此执行程序已执行
shutdown
。
getExecuteExistingDelayedTasksAfterShutdownPolicy()
- 作用:获取有关是否执行现有延迟任务的策略,即使此执行程序已执行
shutdown
。
getQueue()
- 作用:返回此执行程序使用的任务队列。
- 作用:获取有关是否应在取消时立即从工作队列中删除已取消任务的策略。
schedule(Runnable command, long delay, TimeUnit unit)
- 作用:提交在给定延迟后启用的一次性任务。
schedule(Callable<V> callable, long delay, TimeUnit unit)
- 作用:提交一个返回值的一次性任务,该任务在给定的延迟后变为启用状态。
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
- 作用:提交在给定的初始延迟后首先启用的定期操作,随后在给定的时间段内启用; 也就是说,执行将在之后
initialDelay
,然后initialDelay + period
,initialDelay + 2 * period
等等开始。
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
- 作用:提交在给定的初始延迟之后首先启用的定期动作,并且随后在一次执行的终止和下一次执行的开始之间给定延迟。
setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)
- 作用:设置是否继续执行现有周期性任务的策略,即使此执行程序已执行
shutdown
。
setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)
- 作用:设置是否执行现有延迟任务的策略,即使此执行程序已执行
shutdown
。
setRemoveOnCancelPolicy(boolean value)
- 作用:设置关于是否应在取消时立即从工作队列中删除已取消任务的策略。
shutdown()
- 作用:启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。
- 作用:尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。
- 作用:提交Runnable任务以执行并返回表示该任务的Future。
submit(Runnable task, T result)
- 作用:提交Runnable任务以执行并返回表示该任务的Future。
- 作用:提交值返回任务以执行并返回表示任务的挂起结果的Future。
二、使用方法
/**
* 定时任务
*/
private ScheduledThreadPoolExecutor scheduled;
if (scheduled == null) {
scheduled = new ScheduledThreadPoolExecutor(2);
}
//延时1s,每隔300000(5分钟)毫秒执行一次run方法
if (scheduled != null) {
/**
* 0表示首次执行任务的延迟时间,5表示每次执行任务的间隔时间,TimeUnit.MINUTES执行的时间间隔数值单位
* 间隔单位毫秒:TimeUnit.MILLISECONDS
* 间隔单位秒:TimeUnit.SECONDS
* 间隔单位分钟:TimeUnit.MINUTES
* 间隔单位小时:TimeUnit.HOURS
* 间隔单位天:TimeUnit.DAYS
* scheduleAtFixedRate和scheduleWithFixedDelay的区别:
* scheduleAtFixedRate:是上一个任务开始执行之后延迟设定时间再执行,是从上一个任务开始时计时,
* 但对于运行时长超过延迟时长的任务,会等上一个任务执行完之后,下一个任务才开始执行,
* 此时,延时没有任何意义。
* scheduleWithFixedDelay:scheduleWithFixedDelay是在上一个任务结束执行之后延迟设定时间再执行,
* 是从上一个任务结束时开始计算。
*/
scheduled.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
//这里执行定时任务
}
}, 0, 5, TimeUnit.MINUTES);
}
三、scheduleAtFixedRate和scheduleWithFixedDelay的区别
- scheduleAtFixedRate:是上一个任务开始执行之后延迟设定时间再执行,是从上一个任务开始时计时, 但对于运行时长 超过延迟时长的任务,会等上一个任务执行完之后,下一个任务才开始执行, 此时,延时没有任 何意义。
- scheduleWithFixedDelay:scheduleWithFixedDelay是在上一个任务结束执行之后延迟设定时间再执行, 是从上一个任务 结束时开始计算。