溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java中如何實(shí)現(xiàn)ScheduledExecutorService定時任務(wù)

發(fā)布時間:2021-08-17 09:01:11 來源:億速云 閱讀:515 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“Java中如何實(shí)現(xiàn)ScheduledExecutorService定時任務(wù)”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Java中如何實(shí)現(xiàn)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 是基于固定時間間隔進(jìn)行任務(wù)調(diào)度,ScheduleWithFixedDelay 取決于每次任務(wù)執(zhí)行的時間長短,是基于不固定時間間隔進(jìn)行任務(wù)調(diào)度。

以上是“Java中如何實(shí)現(xiàn)ScheduledExecutorService定時任務(wù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI