Java中的定时任务ScheduledExecutorService Executors.newScheduledThreadPool
1. scheduleAtFixedRate
表示以固定频率执行的任务,如果当前任务耗时较多,超过定时周期period,则当前任务结束后会立即执行。
2. scheduleWithFixedDelay
表示以固定延时执行任务,延时是相对当前任务结束为起点计算开始时间。
3. 实验测试代码:
//定时Executors,重新自定义ThreadFactory,这样便于通过线程名称来识别
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1,
new ThreadFactory() {
int index = 0;
public Thread newThread(Runnable r) {
index++;
return new Thread(r,""+index);
}
});
/**
* FixedRate表示会周期性的执行,如果执行时间长超过period的话,下一个周期会立即执行
*/
//scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
// public void run() {
// System.out.println("exectue start time =" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
// System.out.println("scheule at fixed run...,threadName=" + Thread.currentThread().getName());
// try {
// Thread.sleep(10 * 1000);
// }catch (Exception e){
//
// }
// System.out.println("finish time=" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
// }
//},0,5,TimeUnit.SECONDS);
/**
* fixedDelay的话,是在上一次执行完再delay时间后执行
*/
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
public void run() {
System.out.println("exectue start time =" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
System.out.println("scheule at fixed run...,threadName=" + Thread.currentThread().getName());
try {
Thread.sleep(10 * 1000);
}catch (Exception e){
}
System.out.println("finish time=" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
}
},0,5,TimeUnit.SECONDS);