Java ScheduledExecutorService定時任務(wù)案例講解
ScheduledExecutorService,是基于線程池設(shè)計(jì)的定時任務(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í)行一次job1service.scheduleAtFixedRate(new MyScheduledExecutor('job1'), initialDelay, period, TimeUnit.SECONDS);// 從現(xiàn)在開始2秒鐘之后,每隔2秒鐘執(zhí)行一次job2service.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)度。
到此這篇關(guān)于Java ScheduledExecutorService定時任務(wù)案例講解的文章就介紹到這了,更多相關(guān)Java ScheduledExecutorService定時任務(wù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python網(wǎng)絡(luò)編程之ZeroMQ知識總結(jié)2. Python查找算法之分塊查找算法的實(shí)現(xiàn)3. python基于tkinter點(diǎn)擊按鈕實(shí)現(xiàn)圖片的切換4. .NET 中配置從xml轉(zhuǎn)向json方法示例詳解5. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例6. python之cur.fetchall與cur.fetchone提取數(shù)據(jù)并統(tǒng)計(jì)處理操作7. Python TestSuite生成測試報(bào)告過程解析8. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案
