志在指尖
用双手敲打未来

定时任务实现方式对比

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();java
}
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的星星最多,别的两个已经两年没更新了

未经允许不得转载:IT技术网站 » 定时任务实现方式对比
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载