Java定时任务框架

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第5天,点击查看活动详情

前言

开发的系统中过程,会有如下的需求:

  • 凌晨生成订单统计报表
  • 定时推送文章、发送邮件
  • 每隔5分钟动态抓取数据更新
  • 每晚定时计算用户当日收益情况并推送给用户
  • .....

通常这些需求我们都是通过定时任务来实现,列举了java中一些常用的的定时任务框架。

定时任务框架

图片.png

TimeTask

从我们开始学习java开始,最先实现定时任务的时候都是采用TimeTask, Timer内部使用TaskQueue的类存放定时任务,它是一个基于最小堆实现的优先级队列。TaskQueue会按照任务距离下一次执行时间的大小将任务排序,保证在堆顶的任务最先执行。

实例代码:

 public static void main(String[] args)
    {
          TimerTask task = new TimerTask() {
              public void run() {
                  System.out.println("当前时间: " + new Date() + "n" +
                          "线程名称: " + Thread.currentThread().getName());
              }
          };
          Timer timer = new Timer("Timer");
          long delay = 5000L;
          timer.schedule(task, delay);
          
          System.out.println("当前时间: " + new Date() + "n" +
                  "线程名称: " + Thread.currentThread().getName());
    }
复制代码

运行结果:

当前时间: Wed Apr 06 22:05:04 CST 2022n线程名称: main
当前时间: Wed Apr 06 22:05:09 CST 2022n线程名称: Timer

复制代码

从结果可以看出,5秒后执行了定时任务。

缺点:

  • TimeTask执行任务只能串行执行,一旦一个任务执行的时间比较长的话将会影响其他任务执行
  • 执行任务过程如果发生异常,任务会直接停止。

随着时间的推移,java的技术也在不断的更新,针对TimeTask的不足,ScheduledExecutorService出现替代了TimeTask。

ScheduledExecutorService

ScheduledExecutorService是一个接口,有多个实现类,比较常用的是ScheduledThreadPoolExecutor。而ScheduledThreadPoolExecutor本身就是一个线程池,其内部使用 DelayQueue 作为任务队列,并且支持任务并发执行。

实例代码:

 public static void main(String[] args) throws InterruptedException
   {
      ScheduledExecutorService executorService =
              Executors.newScheduledThreadPool(3);
      // 执行任务: 每 10秒执行一次
      executorService.scheduleAtFixedRate(() -> {
          System.out.println("执行任务:" + new Date()+",线程名称: " + Thread.currentThread().getName());
      }, 1, 10, TimeUnit.SECONDS);
    }
复制代码

缺点:

  • 尽量避免用Executors方式去创建线程池,因为jdk自带线程池内部使用的的队列的比较大,很容易出现OOM。

  • 定时任务是基于JVM单机内存形式的,一旦重启定时任务就消失了。

  • 无法支持cron表达式实现丰富的定时任务。

Spring Task

学习了Spring之后,开始使用了Spring 自带的Task。Spring Framework 自带定时任务,提供了 cron 表达式来实现丰富定时任务配置。

实例代码:

@EnableScheduling
@Component
public class SpringTask
{
    private Logger logger = LoggerFactory.getLogger(SpringTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
            "HH:mm:ss");

    /**
     * fixedRate:固定速率执行。每5秒执行一次。
     */
    @Scheduled(fixedRate = 5000)
    public void invokeTaskWithFixedRate()
    {
        logger.info("Fixed Rate Task :  Current Time  is  {}",
                dateFormat.format(new Date()));
    }

    /**
     * fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
     */
    @Scheduled(fixedDelay = 2000)
    public void invokeTaskWithFixedDelay()
    {
        try
        {
            TimeUnit.SECONDS.sleep(3);
            logger.info("Fixed Delay Task : Current Time  is  {}",
                    dateFormat.format(new Date()));
        }
        catch (InterruptedException e)
        {
            logger.error("invoke task error",e);
        }
    }

    /**
     * initialDelay:初始延迟。任务的第一次执行将延迟5秒,然后将以5秒的固定间隔执行。
     */
    @Scheduled(initialDelay = 5000, fixedRate = 5000)
    public void invokeTaskWithInitialDelay()
    {
        logger.info("Task with Initial Delay : Current Time is  {}",
                dateFormat.format(new Date()));
    }

    /**
     * cron:使用Cron表达式,每隔5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void invokeTaskWithCronExpression()
    {
        logger.info("Task Cron Expression:  Current Time  is  {}",
                dateFormat.format(new Date()));
    }
}

复制代码

执行结果:

2022-04-06 23:06:20.945  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Task Cron Expression:  Current Time  is  23:06:20
2022-04-06 23:06:22.557  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Task with Initial Delay : Current Time is  23:06:22
2022-04-06 23:06:22.557  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Fixed Rate Task :  Current Time  is  23:06:22
2022-04-06 23:06:25.955  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Fixed Delay Task : Current Time  is  23:06:25
2022-04-06 23:06:25.955  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Task Cron Expression:  Current Time  is  23:06:25
2022-04-06 23:06:27.555  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Task with Initial Delay : Current Time is  23:06:27
2022-04-06 23:06:27.556  INFO 14604 --- [   scheduling-1] com.fw.task.SpringTask                   : Fixed Rate Task :  Current Time  is  23:06:27

复制代码

@EnableScheduling需要开启定时任务,@Scheduled(cron = "0/5 * * * * ?")配置定时任务的规则。cron表达式支持丰富定时任务配置,不熟悉的的可以查看 cron.qqe2.com/

优点:

使用简单方便,支持各种复杂的定时任务配置

缺点:

  • 基于单机形式定时任务,一旦重启定时任务就消失了。

  • 定时任务默认是单线程执行任务,如果需要并行执行需要开启@EnableAsync。

  • 没有统一的图形化任务调度的管理,无法控制定时任务

结语

任何技术的出现都有它的价值,技术没有最好的,只有最合适的。我们要针对不同的需求选择最合适的技术,切莫过度架构设计。本文讲解了单机环境实现定时任务的技术,下一篇将开始讲解分布式的任务框架。

猜你喜欢

转载自juejin.im/post/7083510602441687054