多线程并行处理定时任务时,Timer运行多个TimeTask时,只要其中之一没有捕获抛出的异常,其它任务便会自动终止运行,使用ScheduledExecutorService则没有这个问题。
//org.apache.commons.lang3.concurrent.BasicThreadFactory
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern(“example-schedule-pool-%d”).daemon(true).build());
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//do something
}
},initialDelay,period, TimeUnit.HOURS);
参考资料
https://blog.csdn.net/wangmx1993328/article/details/80840598
例子 创建并执行在给定延迟后启用的 一次性操作
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
System.out.println(“3秒后开始执行计划线程池服务…” + new Date());
scheduledExecutorService.schedule(new MyThread(), 3, TimeUnit.SECONDS);
————————————————