程序中,需要每秒钟定时去跑点东西,但觉得用quartz又有点大材小用,于是就是用了:
Timer timer = new Timer();
timer.schedule(() -> {//执行些东西},1000,1000);
然后阿里巴巴提示说,让用 ScheduledExecutorService 替代 Timer,于是就试试效果。
这里有个要求,必须按顺序去执行,虽然程序是每秒执行一次,但是如果执行过程比较慢(比如程序需要执行10秒才完成),那就必须等待执行完,才执行下一次。
测试代码:
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(()->{
try {
//加上这个,看看1没执行完,会不会马上执行2,意即会不会开个新线程去执行
Thread.sleep(1000);
}catch (Exception ex){
}
System.out.println(Thread.currentThread().getName()+" run : "+ System.currentTimeMillis());
}, 0, 100, TimeUnit.MILLISECONDS);
//0延时,每隔100毫秒执行一次
}
执行情况:
image.png
执行结果符合预期:ScheduledExecutorService只开了一个线程去跑,而且虽然我设置了每100毫秒执行一次,但我的程序要执行1秒,所以运行时,会是每秒跑一次。