java 定时任务 区别_定时任务实现方式对比

1.守时使命完成方法比照

1.1.Timer

代码例子如下

publicstaticvoidmain(String[]args){

DateTimeFormatterformatter=DateTimeFormatter.ofPattern(“yyyy-MM-ddHH:mm:ss”);

LocalDateTimelocalDateTime=LocalDateTime.now();

Stringformat=localDateTime.format(formatter);

System.out.println(“1:”+format);

Timertimer=newTimer();for(inti=0;i<2;i++){

timer.schedule(newTimerTask(){

@Overridepublicvoidrun(){try{

Thread.sleep(3000);

}catch(InterruptedExceptione){

e.printStackTrace();68db9b0395a995b9042ad98ce4b08c2a.png

}

System.out.println(“Threadname:”+Thread.currentThread().getName());

LocalDateTimelocalDateTime=LocalDateTime.now();

Stringformat=localDateTime.format(formatter);

System.out.println(“2:”+format);

}

},3000);

}

localDateTime=LocalDateTime.now();

format=localDateTime.format(formatter);

System.out.println(“3:”+format);

}

成果

1:2019-10-1417:35:133:2019-10-1417:35:13Threadname:Timer-02:2019-10-1417:35:19Threadname:Timer-02:2019-10-1417:35:22

能够看出同一个Timer的守时使命,后台就一个线程办理使命分配,遇到使命堵塞,可能导致下一个使命推迟

且如果使命发生反常,体系就终止了

1.2.ScheduledExecutorService

为了解决Timer的问题,ScheduledExecutorService做了改进,选用了线程池的守时使命行列,实际运用的也是最小堆排序

代码如下

privatestaticDateTimeFormatterformatter=DateTimeFormatter.ofPattern(“yyyy-MM-ddHH:mm:ss”);publicstaticvoidmain(String[]args){//timerTest();print(“1:”);

ScheduledExecutorServiceservice=newScheduledThreadPoolExecutor(2);for(inti=0;i<2;i++){

service.schedule(newRunnable(){

@Overridepublicvoidrun(){try{

Thread.sleep(3000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

System.out.println(“Threadname:”+Thread.currentThread().getName());

print(“2:”);

}

},3,TimeUnit.SECONDS);

}

print(“3:”);

service.shutdown();

}privatestaticvoidprint(Strings){

LocalDateTimelocalDateTime=LocalDateTime.now();

Stringformat=localDateTime.format(formatter);

System.out.println(s+format);

}

成果

1:2019-10-1511:53:543:2019-10-1511:53:54Threadname:pool-1-thread-12:2019-10-1511:54:00Threadname:pool-1-thread-22:2019-10-1511:54:00

明白它的推迟原理和Timer一样,能够知道如果我把核心线程数改成1,则效果和Timer类似

成果如下,两个使命推迟3秒,前一个使命会导致后一个使命推迟

1:2019-10-1511:57:403:2019-10-1511:57:40Threadname:pool-1-thread-12:2019-10-1511:57:46Threadname:pool-1-thread-12:2019-10-1511:57:49

它的优势在于能够多线程执行,一定程度上防止使命间互相影响,一起单个使命反常不影响其它使命

1.3.时间轮(推迟音讯)

1

本质是环形数组,比如上述8个节点的时间轮,每个节点寄存使命行列,比如我们需要新建5s推迟的使命,就放5的节点,新建10s推迟的使命就放2的节点,设推迟时间为n,则节点位置为n%8,一起需记下轮询圈数n/8

优势:当使命数量十分多的时候选用这样环形数组加行列是个效率比较高的挑选

想要了解更多时间轮完成,能够参考文章下的参考博客

1.4.分布式守时使命

github上也有些开源的分布式守时使命的方案,能够直接运用

如xxl_job,elastic-job-lite,light-task-scheduler,以哪个火用哪个的准则,那仍是xxl_job的星星最多,别的两个已经两年没更新了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值