定时/延迟任务线程池ScheduledExecutorService类常用方法
定时/延迟任务ScheduledExecutorService类
ScheduledExecutorService的用法主要有三个:
延迟任务
循环任务
装逼
通过静态方法创建ScheduledExecutorService的实例
private static final ScheduledExecutorService mScheduledExecutorService = Executors.newScheduledThreadPool(4);
延时任务
mScheduledExecutorService.schedule(() -> System.out.println("lzp"+"first task"), 1, TimeUnit.SECONDS);
循环任务
按照上一次任务的发起时间计算下一次任务的开始时间
mScheduledExecutorService.scheduleAtFixedRate(() -> {
System.out.println("lzp"+"first:" + System.currentTimeMillis() / 1000);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
以上一次任务的结束时间计算下一次任务的开始时间
mScheduledExecutorService.scheduleWithFixedDelay(() -> {
System.out.println("lzp"+"scheduleWithFixedDelay:" + System.currentTimeMillis() / 1000);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
测试类
package com.test.api.modules.test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author maverick
*/
public class ScheduledExecutorServiceTest {
// 通过静态方法创建ScheduledExecutorService的实例
private static final ScheduledExecutorService mScheduledExecutorService = Executors.newScheduledThreadPool(4);
public static void main(String[] args) {
// 延时任务
mScheduledExecutorService.schedule(() -> System.out.println("lzp"+"first task"), 1, TimeUnit.SECONDS);
// 循环任务,按照上一次任务的发起时间计算下一次任务的开始时间
mScheduledExecutorService.scheduleAtFixedRate(() -> {
System.out.println("lzp"+"first:" + System.currentTimeMillis() / 1000);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
// 循环任务,以上一次任务的结束时间计算下一次任务的开始时间
mScheduledExecutorService.scheduleWithFixedDelay(() -> {
System.out.println("lzp"+"scheduleWithFixedDelay:" + System.currentTimeMillis() / 1000);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
}
}