好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java单机环境实现定时任务技术

前言

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

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

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

定时任务框架

TimeTask

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

实例代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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());

    }

运行结果:

?

1

2

3

当前时间: 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 作为任务队列,并且支持任务并发执行。

实例代码:

?

1

2

3

4

5

6

7

8

9

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 表达式来实现丰富定时任务配置。

实例代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

@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表达式支持丰富定时任务配置,不熟悉的的可以查看

优点:

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

缺点:

基于单机形式定时任务,一旦重启定时任务就消失了。 定时任务默认是单线程执行任务,如果需要并行执行需要开启@EnableAsync。 没有统一的图形化任务调度的管理,无法控制定时任务

结语

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

到此这篇关于Java单机环境实现定时任务技术的文章就介绍到这了,更多相关Java定时任务框架内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://juejin.cn/post/7083510602441687054

查看更多关于Java单机环境实现定时任务技术的详细内容...

  阅读:25次