亚洲精品一区二区手机在线观看,久久久久久夜,国产精品人人爽97欧美视频,超碰人人婷婷,国产剧免费观看高清电视剧,99av亚洲综合一区二区,91精品欧美久久久久,久久婷婷五月综合色D啪

定時任務實現(xiàn)方式對比

時間:2023-05-17

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的守時使命,后臺就一個線程辦理使命分配,遇到使命堵塞,可能導致下一個使命推遲
且如果使命發(fā)生反常,體系就終止了
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一樣,能夠知道如果我把核心線程數(shù)改成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
它的優(yōu)勢在于能夠多線程執(zhí)行,一定程度上防止使命間互相影響,一起單個使命反常不影響其它使命
1.3.時間輪(推遲音訊)
1
本質是環(huán)形數(shù)組,比如上述8個節(jié)點的時間輪,每個節(jié)點寄存使命行列,比如我們需要新建5s推遲的使命,就放5的節(jié)點,新建10s推遲的使命就放2的節(jié)點,設推遲時間為n,則節(jié)點位置為n%8,一起需記下輪詢圈數(shù)n/8
優(yōu)勢:當使命數(shù)量十分多的時候選用這樣環(huán)形數(shù)組加行列是個效率比較高的挑選
想要了解更多時間輪完成,能夠參考文章下的參考博客
1.4.分布式守時使命
github上也有些開源的分布式守時使命的方案,能夠直接運用
如xxl_job,elastic-job-lite,light-task-scheduler,以哪個火用哪個的準則,那仍是xxl_job的星星最多,別的兩個已經(jīng)兩年沒更新了

文章標簽:

Copyright ? 2016 廣州思洋文化傳播有限公司,保留所有權利。 粵ICP備09033321號

與項目經(jīng)理交流
掃描二維碼
與項目經(jīng)理交流
掃描二維碼
與項目經(jīng)理交流
ciya68