ScheduledExecutorService扩展了ExecutorService接口,提供定时执行任务的功能(类似Timer)。
API 说明
Method | Desc |
---|---|
schedule(Callable<V> callable, long delay, TimeUnit unit) | 创建并执行在给定延迟后启用的 ScheduledFuture。 |
schedule(Runnable command, long delay, TimeUnit unit) | 创建并执行在给定延迟后启用的一次性操作。 |
scheduleAtFixedRate(Runnable command, long initialDelay,long period, TimeUnitunit) | 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。 |
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit) | 创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。 |
schedule方法被用来延迟指定时间来执行某个指定任务。如果你需要周期性重复执行定时任务可以使用scheduleAtFixedRate或者scheduleWithFixedDelay方法,它们不同的是前者以固定频率执行,后者以相对固定频率执行。
不管任务执行耗时是否大于间隔时间,scheduleAtFixedRate和scheduleWithFixedDelay都不会导致同一个任务并发地被执行。
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
注意事项
通过ScheduledExecutorService执行的周期任务,如果任务执行过程中抛出了异常,那么过ScheduledExecutorService就会停止执行任务,且之后的任务也不会被执行。
If any execution of the task encounters an exception, subsequent executions are suppressed.
简单示例
1、定时执行
package com.bytebeats.codelab;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* ${DESCRIPTION}
*
* @author Ricky Fung
* @create 2016-08-15 23:38
*/
public class ScheduledExecutorServiceDemo {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
System.out.println("count...");
}
}, 1, TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(5);
scheduledExecutorService.shutdown();
}
}
2、固定频率执行任务
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("count...");
}
}, 1, 2, TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(10);
scheduledExecutorService.shutdown();
3、固定时间间隔执行任务
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("count...");
}
}, 1, 1, TimeUnit.SECONDS);
参考资料
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html