继承ThreadPoolExecutor,实现ScheduledExecutorService接口。
虽然此类继承自 ThreadPoolExecutor,但是几个继承的调整方法对此类并无作用。特别是,因为它作为一个使用 corePoolSize 线程和一个无界队列的固定大小的池,所以调整 maximumPoolSize 没有什么效果。
简单实例:这个例子跟使用 ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 1000,TimeUnit.SECONDS, queue); 类似。
public class TestScheduledThreadPoolExecutor {
public static void main(String[] args) {
ScheduledThreadPoolExecutor exec=new ScheduledThreadPoolExecutor( 1 );
exec.scheduleAtFixedRate(new Runnable(){ //每隔一段时间就触发异常
@Override
public void run() {
throw new RuntimeException();
}}, 1000 , 5000 , TimeUnit.MILLISECONDS);
exec.scheduleAtFixedRate(new Runnable(){ //两者是互不影响的
@Override
public void run() {
System.out.println(System.nanoTime());
}}, 1000 , 2000 , TimeUnit.MILLISECONDS);
}
}
schedule
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
-
从接口
ScheduledExecutorService
复制的描述 - 创建并执行在给定延迟后启用的一次性操作。
-
-
指定者:
-
接口
ScheduledExecutorService
中的schedule
-
接口
-
-
参数:
-
command
- 要执行的任务 -
delay
- 从现在开始延迟执行的时间 -
unit
- 延迟参数的时间单位
返回:
-
表示挂起任务完成的 ScheduledFuture,并且其
get()
方法在完成后将返回null
-
scheduleAtFixedRate
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
-
从接口
ScheduledExecutorService
复制的描述 -
创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在
initialDelay
后开始执行,然后在initialDelay+period
后执行,接着在initialDelay + 2 * period
后执行,依此类推。如果任务的任何一个执行遇到异常,则后续执行都会被取消。否则,只能通过执行程序的取消或终止方法来终止该任务。如果此任务的任何一个执行要花费比其周期更长的时间,则将推迟后续执行,但不会同时执行。 -
-
指定者:
-
接口
ScheduledExecutorService
中的scheduleAtFixedRate
-
接口
-
-
参数:
-
command
- 要执行的任务 -
initialDelay
- 首次执行的延迟时间 -
period
- 连续执行之间的周期 -
unit
- initialDelay 和 period 参数的时间单位
返回:
-
表示挂起任务完成的 ScheduledFuture,并且其
get()
方法在取消后将抛出异常
-
getQueue
public BlockingQueue<Runnable> getQueue()
-
返回此执行程序使用的任务队列。此队列中的每个元素都是一个 ScheduledFuture,包括用
execute
所提交的那些任务,出于安排的目的,这些任务用作零延迟ScheduledFuture
的基础。 无法 保证对此队列进行迭代的迭代器会以任务执行的顺序遍历各任务。 -
-
覆盖:
-
类
ThreadPoolExecutor
中的getQueue
-
类
-
-
返回:
- 任务队列。
项目中使用
long delay = DateUtil.compareTimeInMillis(matchTask.getExecTime(), Calendar.getInstance()); //与当前系统时间之间的延时
ScheduledFuture<?> futureTask = threadExec.schedule(matchTask, delay, TimeUnit.MILLISECONDS);