ScheduledExecutorService 是jdk1.5之后提供的替代Timer的一个类。下面为大家提供一个简单的使用例子。
使用ScheduledExecutorService 需注意一点,如果执行过程中一点有一个任务发现异常,程序会终止执行。因此最好自己将异常捕获处理掉。
下面是jdk中的注释:
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
示例如下,ScheduledExecutorService 提供了很多方法,这里只说明一种:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test implements Runnable {
private static LocalDateTime ldt = LocalDateTime.now();
private static DateTimeFormatter dtf = DateTimeFormatter
.ofPattern("yyyy-MM-dd hh:mm:ss");
public static void main(String[] args) {
ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(2);
Test test1 = new Test();
// 第一个参数:需要执行的任务,第二个参数:第一次执行延迟的时间,
// 第三个参数:间隔时间,第四个参数:计量单位,这里选择秒
ses.scheduleAtFixedRate(test1, 1, 2, TimeUnit.SECONDS);
System.out.println(ldt.format(dtf));
}
@Override
public void run() {
try {
LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter
.ofPattern("yyyy-MM-dd hh:mm:ss");
System.out.println(ldt.format(dtf) + "执行");
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果: