继承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
- 延迟参数的时间单位
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 参数的时间单位
get()
方法在取消后将抛出异常
getQueue
public BlockingQueue<Runnable> getQueue()
execute
所提交的那些任务,出于安排的目的,这些任务用作零延迟
ScheduledFuture
的基础。
无法
保证对此队列进行迭代的迭代器会以任务执行的顺序遍历各任务。
ThreadPoolExecutor
中的
getQueue
项目中使用
long delay = DateUtil.compareTimeInMillis(matchTask.getExecTime(), Calendar.getInstance()); //与当前系统时间之间的延时
ScheduledFuture<?> futureTask = threadExec.schedule(matchTask, delay, TimeUnit.MILLISECONDS);