百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

Java定时任务之ScheduledThreadPoolExecutor

yuyutoo 2024-10-12 00:06 7 浏览 0 评论

ScheduledThreadPoolExecutor是JDK5提供的可执行定时任务的一个工具类,可以在多线程环境下延迟执行任务或者定期执行任务;和Timer类似,它也提供了三种定时模式:

  1. 延迟执行任务
  2. 固定延迟的定期执行(fixed delay)
  3. 按照固定的周期执行(fixed rate)

延迟执行任务

任务将按照给定的时间延迟delay后开始执行;对应的方法如下:

schedule(Runnable command, long delay, TimeUnit unit)  
schedule(Callable<V> callable, long delay, TimeUnit unit)  

下面我们通过一个例子检验下结果是否正确:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        PrintUtil.print("start schedule a task.");
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                PrintUtil.print("task is running.");
            }
}, 5, TimeUnit.SECONDS);

我们计划了一个5秒钟后执行的任务,通过打印结果可以看到确实按照给定时间执行了:

15:44:07--start schedule a task.
15:44:12--task is running.

固定延迟的定期执行

任务第一次按照给定的初始延迟initialDelay执行,后续每一次执行的时间为上一次任务的结束时间加上给定的period后执行;对应的方法如下:

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

同样我们通过一个例子检验下结果是否正确:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        PrintUtil.print("start schedule a task.");
        executor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                PrintUtil.print("task is running.");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
}, 0, 5, TimeUnit.SECONDS);

我们计划了一个定期(每5秒钟)延迟执行的任务,第一次任务立即执行,每次任务执行时长2秒钟,通过打印的日志我们可以看到每次任务开始执行的时间为:上次任务结束时间+5秒钟:

15:55:16--start schedule a task.
15:55:16--task is running.
15:55:18--task is finished.
15:55:23--task is running.
15:55:25--task is finished.
15:55:30--task is running.
15:55:32--task is finished.

按照固定的周期执行

任务第一次按照给定的初始延迟initialDelay执行,后续每一次执行的时间为固定的时间间隔period,如果线程池中工作线程不够则任务顺延执行;对应的方法如下:

scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)

同样我们通过一个例子检验下结果是否正确:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
        PrintUtil.print("start schedule a task.");
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                PrintUtil.print("task is running.");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                PrintUtil.print("task is finished.");
            }
}, 0, 5, TimeUnit.SECONDS);

我们创建了一个核心线程池为10的ScheduledThreadPoolExecutor,并计划了一个定期(每5秒钟)执行一次的任务,过打印的日志我们可以看到每次任务开始执行的时间为:上次任务开始时间+5秒钟:

16:02:43--start schedule a task.
16:02:43--task is running.
16:02:45--task is finished.
16:02:48--task is running.
16:02:50--task is finished.


上面的例子都是计划了一个任务,如果是有多个定时任务同时执行会怎么样呢?

如果线程足够并且CPU资源足够,那就会同时执行,如果线程或者CPU资源不够那只能排队执行了。有兴趣的话可以克隆文末的测试代码,里面提供了一些测试的例子。

底层原理

ScheduledThreadPoolExecutor是如何保证我们计划的任务都是按照正确的时间点执行的呢?

其内部实现了一个阻塞队列DelayedWorkQueue,所有的任务都会放到这个队列里。这个阻塞队列内部通过一个数组来保存这些任务,并且基于最小堆排序,按照每个任务的下次执行时间进行排序,这样就保证了执行线程拿到的这个队列中的第一个元素就是最接近当前时间执行的任务了。

相关的源码如下:

// 保存定时任务的队列
private RunnableScheduledFuture<?>[] queue = new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
// 最小堆排序相关的方法
private void siftUp(int k, RunnableScheduledFuture<?> key)
private void siftDown(int k, RunnableScheduledFuture<?> key)

那时间上是如何保证的呢?

DelayedWorkQueue重写了take和poll方法,利用了AQS的ConditionObject机制使当前线程休眠,等时间到了再唤醒线程去拿第一个任务。

关于AQS和ConditonObject的介绍,可以参考下文末的链接。

public RunnableScheduledFuture<?> take() throws InterruptedException {
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                for (;;) {
                    RunnableScheduledFuture<?> first = queue[0];
                    if (first == null)
                        available.await();
                    else {
                        long delay = first.getDelay(NANOSECONDS);
                        if (delay <= 0)
                            return finishPoll(first);
                        first = null; // don't retain ref while waiting
                        if (leader != null)
                            available.await();
                        else {
                            Thread thisThread = Thread.currentThread();
                            leader = thisThread;
                            try {
                                available.awaitNanos(delay);
                            } finally {
                                if (leader == thisThread)
                                    leader = null;
                            }
                        }
                    }
                }
            } finally {
                if (leader == null && queue[0] != null)
                    available.signal();
                lock.unlock();
            }
}

优点

作为对JDK1.3推出的Timer的替代,ScheduledThreadPoolExecutor有如下优点:

  1. 它支持多个定时任务同时执行,而Timer是单线程执行的
  2. 它通过System.nanoTime()保证了任务执行时间不受操作系统时间变化的影响
  3. 一个定时任务抛出异常,其他定时任务不受影响,而Timer却不支持这一点

Demo代码

src/main/java/net/weichitech/util/ScheduledThreadPoolExecutorDemo.java · 小西学编程/java-learning - Gitee.com

参考文章

Java定时任务之Timer原理解析

JAVA并发之ReentrantLock原理解析

相关推荐

网站建设:从新手到高手

现代化网站应用领域非常广泛,从个人形象网站展示、企业商业网站运作、到政府公益等服务网站,各行各业都需要网站建设。大体上可以归结四类:宣传型网站设计、产品型网站制作、电子商务型网站建设、定制型功能网站开...

JetBrains 推出全新 AI 编程工具 Junie,助力高效开发

JetBrains宣布推出名为Junie的全新AI编程工具。这款工具不仅能执行简单的代码生成与检查任务,还能应对编写测试、验证结果等复杂项目,为开发者提供全方位支持。根据SWEBench...

AI也能写代码!代码生成、代码补全、注释生成、代码翻译轻松搞定

清华GLM技术团队打造的多语言代码生成模型CodeGeeX近期更新了新的开源版本「CodeGeeX2-6B」。CodeGeeX2是多语言代码生成模型CodeGeeX的第二代模型,不同于一代CodeG...

一键生成前后端代码,一个36k星的企业级低代码平台

「企业级低代码平台」前后端分离架构SpringBoot2.x,SpringCloud,AntDesign&Vue,Mybatis,Shiro,JWT。强大的代码生成器让前后端代码一键生成,无需写任...

Gitee 代码托管实战指南:5 步完成本地项目云端同步(附避坑要点)

核心流程拆解:远程仓库的搭建登录Gitee官网(注册账号比较简单,大家自行操作),点击“新建仓库”,建议勾选“初始化仓库”和“设置模板文件”(如.gitignore),避免上传临时文件。...

jeecg-boot 源码项目-强烈推荐使用

JEECGBOOT低代码开发平台...

JetBrains推出全新AI编程工具Junie,强调以开发者为中心

IT之家2月1日消息,JetBrains发文,宣布推出一款名为Junie的全新AI编程工具,官方声称这款AI工具既能执行简单的代码生成与检查等基础任务,也能应对“编写测试、验证结...

JetBrains旗下WebStorm和Rider现已加入“非商用免费”阵营

IT之家10月25日消息,软件开发商JetBrains今日宣布,旗下WebStorm(JavaScript开发工具)和Rider(.NET开发工具)现已加入“非商用免费”阵营。如果...

谈谈websocket跨域

了解websocketwebsocket是HTML5的新特性,在客户端和服务端提供了一个基于TCP连接的双向通道。...

websocket调试工具

...

利用webSocket实现消息的实时推送

1.什么是webSocketwebSocket实现实现推送消息WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。以前的推送技术使用Ajax轮询,浏览器需...

Flutter UI自动化测试技术方案选型与探索

...

为 Go 开发的 WebSocket 库

#记录我的2024#...

「Java基础」Springboot+Websocket的实现后端数据实时推送

这篇文章主要就是实现这个功能,只演示一个基本的案例。使用的是websocket技术。...

【Spring Boot】WebSocket 的 6 种集成方式

介绍...

取消回复欢迎 发表评论: