ScheduledExecutorService - 定时周期执行任务

项目需求

定时调用报警器,对数据进行报警判断

技术选型

单机定时任务技术

  • Timer
  • ScheduledExecutorService
  • Spring Task

分布式定时任务技术

  • Quartz
  • Elastic-Job
  • XXL-JOB
  • PowerJob

程序在单机下运行,故只考虑单机定时任务。前期考虑使用 Timer不过其缺陷较多,比如一个 Timer 一个线程,这就导致 Timer 的任务的执行只能串行执行,一个任务执行时间过长的话会影响其他任务(性能非常差),再比如发生异常时任务直接停止(Timer 只捕获了 InterruptedException )。

ScheduledExecutorService使用

ScheduledThreadPoolExecutor继承自ThreadPoolExecutor。它主要用来在给定的延迟之后运 行任务,或者定期执行任务。ScheduledThreadPoolExecutor的功能与Timer类似,但 ScheduledThreadPoolExecutor功能更强大、更灵活。Timer对应的是单个后台线程,而 ScheduledThreadPoolExecutor可以在构造函数中指定多个对应的后台线程数。

ScheduledExecutorService接口是java线程池中最重要的几个接口之一。
在这里插入图片描述
它除了支持原生线程池的功能之外,同时支持定时任务处理的功能。
在JDK中为它提供了一个默认的实现类:ScheduledThreadPoolExecutor。

ScheduledExecutorService包括三个方法:schedule()、scheduleAtFixedRate()、scheduleWithFixedDelay()。

schedule()方法

定义:在给定的延时之后,创建并执行一个启动一次性动作。

/**
*
     * @param command the task to execute 要执行的任务
     * @param delay the time from now to delay execution 从现在开始推迟执行的时间
     * @param unit the time unit of the delay parameter 延迟参数的时间单位
**/
public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);

scheduleAtFixedRate()方法 (以固定周期运行)

相比于schedule()方法,多了一个参数period,可以指定周期执行。一个周期 = 任务执行完成的时间 + 两次任务的间隔时间

/**
*
     * @param command the task to execute 要执行的任务
     * @param initialDelay the time to delay first execution 从现在开始推迟执行的时间
     * @param period the period between successive executions 延迟首次执行的时间
     * @param unit the time unit of the initialDelay and period parameters 延迟参数的时间单位
  *
  **/
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

ScheduleWithFixedDelay()方法

/**
     * @param command the task to execute 要执行的任务
     * @param initialDelay the time to delay first execution 从现在开始推迟执行的时间
     * @param delay the delay between the termination of one 
     * execution and the commencement of the next  一个执行的终止和下一个执行的开始之间的延迟
     * @param unit the time unit of the initialDelay and delay parameters 延迟参数的时间单位
 **/
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);

参考文章:
Java多线程学习(八)线程池与Executor 框架
Spring Job?Quartz?XXL-Job?年轻人才做选择,艿艿全莽~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值