Java ScheduledExecutorService定時任務(wù)案例講解
一、ScheduledExecutorService 設(shè)計思想
ScheduledExecutorService,是基于線程池設(shè)計的定時任務(wù)類,每個調(diào)度任務(wù)都會分配到線程池中的一個線程去執(zhí)行,也就是說,任務(wù)是并發(fā)執(zhí)行,互不影響。
需要注意,只有當(dāng)調(diào)度任務(wù)來的時候,ScheduledExecutorService才會真正啟動一個線程,其余時間ScheduledExecutorService都是出于輪詢?nèi)蝿?wù)的狀態(tài)。
1、線程任務(wù)
class MyScheduledExecutor implements Runnable { private String jobName; MyScheduledExecutor() { } MyScheduledExecutor(String jobName) { this.jobName = jobName; } @Override public void run() { System.out.println(jobName + " is running"); } }
2、定時任務(wù)
public static void main(String[] args) { ScheduledExecutorService service = Executors.newScheduledThreadPool(10); long initialDelay = 1; long period = 1; // 從現(xiàn)在開始1秒鐘之后,每隔1秒鐘執(zhí)行一次job1 service.scheduleAtFixedRate(new MyScheduledExecutor("job1"), initialDelay, period, TimeUnit.SECONDS); // 從現(xiàn)在開始2秒鐘之后,每隔2秒鐘執(zhí)行一次job2 service.scheduleWithFixedDelay(new MyScheduledExecutor("job2"), initialDelay, period, TimeUnit.SECONDS); }
ScheduledExecutorService 中兩種最常用的調(diào)度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次執(zhí)行時間為上一次任務(wù)開始起向后推一個時間間隔,即每次執(zhí)行時間為 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次執(zhí)行時間為上一次任務(wù)結(jié)束起向后推一個時間間隔,即每次執(zhí)行時間為:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可見,ScheduleAtFixedRate 是基于固定時間間隔進行任務(wù)調(diào)度,ScheduleWithFixedDelay 取決于每次任務(wù)執(zhí)行的時間長短,是基于不固定時間間隔進行任務(wù)調(diào)度。
到此這篇關(guān)于Java ScheduledExecutorService定時任務(wù)案例講解的文章就介紹到這了,更多相關(guān)Java ScheduledExecutorService定時任務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot 設(shè)置傳入?yún)?shù)非必要的操作
這篇文章主要介紹了SpringBoot 設(shè)置傳入?yún)?shù)非必要的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02