我利用的是线程池的scheduleAtFixedRate()
方法,来实现定时任务类似功能。
定时任务类:
/**
* 监听任务
*
* @author lixiang
* @date 2019年04月17日 - 10:08
* @history 2019年04月17日 - 10:08 lixiang create.
*/
public class MonitorTask {
/**
* 监听次数计数器
*/
private int index = 0;
/**
* 最大监听次数
*/
private int maxTimes = 5;
public void doMonitor() {
/**
* 监听任务线程池
*/
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("monitor-pool-%d").daemon(true).build());
// 设置信号量同时执行的线程数是1
final Semaphore semaphore = new Semaphore(1);
Runnable runnable = () -> {
try {
// 获取锁
semaphore.acquire();
System.out.println("======监听线程开始========");
index += 1;
// TODO: 做你想做的
System.out.println("已监听次数:" + index);
} catch (InterruptedException e) {
System.out.println("获取信号量异常!!!");
e.printStackTrace();
} finally {
if (index > maxTimes) {
index = 0;
System.out.println("已监听达到最大次数,现关闭线程池!!!");
scheduledExecutorService.shutdown();
}
// TODO: 根据自定义的条件关闭线程池
System.out.println("======监听线程结束========");
// 释放锁
semaphore.release();
}
};
/**
* 首次延迟5s启动,每隔5s执行一次
*/
scheduledExecutorService.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.SECONDS);
}
}
测试方法类
/**
* 测试类
*
* @author lixiang
* @date 2019年04月17日 - 10:24
* @history 2019年04月17日 - 10:24 lixiang create.
*/
public class MainTest {
public static void main(String[] args) {
System.out.println("总调度开始");
MonitorTask monitorTask = new MonitorTask();
new Thread(() ->
monitorTask.doMonitor()).start();
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("总调度结束");
}
}
运行效果
如果有问题还请不吝赐教!!!