ScheduledThreadPoolExecutor有四个构造方法,如下所示:
ScheduledThreadPoolExecutor(int corePoolSize) |
|
---|---|
ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) |
|
ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) |
|
ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) |
|
decorateTask(Runnable runnable,RunnableScheduledFuture
作用:修改或替换用于执行runnable的任务。
decorateTask(Callable
execute(Runnable command)
command
所需的延迟为零。getContinueExistingPeriodicTasksAfterShutdownPolicy()
shutdown
。getExecuteExistingDelayedTasksAfterShutdownPolicy()
shutdown
。getQueue()
getRemoveOnCancelPolicy()
schedule(Runnable command, long delay, TimeUnit unit)
schedule(Callable
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()
shutdownNow()
submit(Runnable task)
submit(Runnable task, T result)
submit(Callable
/**
* 定时任务
*/
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);
}