博客
关于我
线程池-----ScheduledExecutorService实现定时任务
阅读量:348 次
发布时间:2019-03-04

本文共 3273 字,大约阅读时间需要 10 分钟。

Java ExecutorService中的定时任务调度接口

在Java的ExecutorService中,scheduleAtFixedRatescheduleWithFixedDelay是两个关键接口,用于实现定时任务的调度。理解这两个接口的区别对于优化应用性能至关重要。本文将深入探讨scheduleAtFixedRate的实现和应用。

1. scheduleAtFixedRate的参数解析

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)方法定义了一个固定时间间隔的任务调度机制。其参数含义如下:

  • command:执行线程,负责实现具体的任务逻辑。
  • initialDelay:初始化延时,指任务首次执行前的等待时间。
  • period:固定时间间隔,表示每次任务执行之间的等待时间。
  • unit:计时单位,定义了时间的表示方式(如毫秒、秒等)。

2. 固定时间间隔任务调度示例

以下示例展示了如何使用scheduleAtFixedRate实现每隔100毫秒执行一次任务的定时调度:

import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ScheduledExecutorServiceTest {    public static void main(String[] args) {        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();        executorService.scheduleAtFixedRate(            new Runnable() {                @Override                public void run() {                    System.out.println("run " + System.currentTimeMillis());                }            },            0,  // 初始化延时为0ms            100, // 每次执行间隔100ms            TimeUnit.MILLISECONDS        );    }}

运行上述代码,会看到每隔100ms输出一次“run”并带有当前时间戳。

3. 固定时间任务调度场景

在实际应用中,尤其是需要在特定时间点执行任务的情况下,可以通过scheduleAtFixedRate实现。例如,可以设置每天凌晨3点执行一次耗时较长的资源整理任务。

import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ExecutorTest {    public static final ScheduledExecutorService service = Executors.newScheduledThreadPool(4);    public static void main(String[] args) {        long oneDay = 24 * 60 * 60 * 1000; // 一天的时间        long initDelay = getTimeMillis("03:00:00") - System.currentTimeMillis();        initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;        service.scheduleAtFixedRate(            new MyScheduled1(),            initDelay,            oneDay,            TimeUnit.MILLISECONDS        );        service.scheduleAtFixedRate(            new MyScheduled2(),            initDelay,            oneDay,            TimeUnit.MILLISECONDS        );    }    private static long getTimeMillis(String time) {        try {            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");            DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");            Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);            return curDate.getTime();        } catch (ParseException e) {            e.printStackTrace();        }        return 0;    }}public class MyScheduled1 implements Runnable {    @Override    public void run() {        System.out.println("my scheduled 01-----");    }}public class MyScheduled2 implements Runnable {    @Override    public void run() {        System.out.println("my scheduled 02 ------");    }}

4. 与scheduleWithFixedDelay的区别

scheduleWithFixedDelayscheduleAtFixedRate的主要区别在于任务调度的机制:

  • scheduleAtFixedRate:基于固定时间间隔进行任务调度,每次任务执行之间等待固定时间。
  • scheduleWithFixedDelay:基于任务执行完成后的延迟时间进行调度,下一次任务执行的时间取决于上一次任务的执行时间。

这种区别使得scheduleAtFixedRate适用于需要严格按照固定时间间隔执行任务的场景,而scheduleWithFixedDelay则适用于任务执行时间不确定的场景。

5. 总结

通过本文的分析,可以看出scheduleAtFixedRate是一个强大的工具,适用于需要在固定时间间隔内执行任务的场景。在实际应用中,可以根据任务的执行需求选择合适的调度接口,以优化资源利用率和应用性能。

转载地址:http://xybe.baihongyu.com/

你可能感兴趣的文章
POI解析Excel【poi的坑——空行处理】
查看>>
POI:POI+JXL实现xls文件添加水印
查看>>
POI:POI实现docx文件添加水印
查看>>
POJ 1006
查看>>
Quartz中时间表达式的设置-----corn表达式
查看>>
poj 1035
查看>>
POJ 1061 青蛙的约会 (扩展欧几里得)
查看>>
Quartz2.2.1简单使用
查看>>
POJ 1080 Human Gene Functions(DP:LCS)
查看>>
Quant 开源项目教程
查看>>
POJ 1088 滑雪
查看>>
POJ 1095 Trees Made to Order
查看>>
POJ 1113 Wall(计算几何--凸包的周长)
查看>>
poj 1125Stockbroker Grapevine(最短路)
查看>>
Qualitor processVariavel.php 未授权命令注入漏洞复现(CVE-2023-47253)
查看>>
poj 1151 (未完成) 扫描线 线段树 离散化
查看>>
POJ 1151 / HDU 1542 Atlantis 线段树求矩形面积并
查看>>
poj 1163 数塔
查看>>
POJ 1177 Picture(线段树:扫描线求轮廓周长)
查看>>
Qualitor checkAcesso.php 任意文件上传漏洞复现(CVE-2024-44849)
查看>>