一、概念
定時計劃任務(wù)功能在java中主要使用的就是timer對象,它在內(nèi)部使用多線程的方式進行處理,所以它和多線程技術(shù)還是有非常大的關(guān)聯(lián)的。在jdk中timer類主要負責計劃任務(wù)的功能,也就是在指定的時間開始執(zhí)行某一個任務(wù),但封裝任務(wù)的類卻是timertask類。
通過繼承 timertask 類 并實現(xiàn) run() 方法來自定義要執(zhí)行的任務(wù):
1
2
3
4
5
6
7
8
|
public class mytask extends timertask { @override public void run() { dateformat dateformat = timeutil.df.get(); system.out.println( "我的任務(wù)運行了" + dateformat.format( new date())); } } |
通過執(zhí)行timer.schedule(timertask task,date time) 在執(zhí)行時間運行任務(wù):
1
2
3
4
5
6
7
8
|
public class run { private static timer timer= new timer(); public static void main(string[] args) throws parseexception { timer.schedule( new mytask(), timeutil.df.get().parse( "2017-09-14 09:19:30" )); } } |
備注:時間轉(zhuǎn)換工具類,保證線程安全:
1
2
3
4
5
6
7
8
9
|
public class timeutil { public static final threadlocal<dateformat> df = new threadlocal<dateformat>() { @override protected dateformat initialvalue() { return new simpledateformat( "yyyy-mm-dd hh:mm:ss" ); } }; } |
二、timer類注意事項
1、創(chuàng)建一個 timer 對象就是新啟動了一個線程,但是這個新啟動的線程,并不是守護線程,它一直在后臺運行,通過如下 可以將新啟動的 timer 線程設(shè)置為守護線程。
1
|
private static timer timer= new timer( true ); |
2、提前:當計劃時間早于當前時間,則任務(wù)立即被運行。
3、延遲:timertask 是以隊列的方式一個一個被順序運行的,所以執(zhí)行的時間和你預(yù)期的時間可能不一致,因為前面的任務(wù)可能消耗的時間較長,則后面的任務(wù)運行的時間會被延遲。延遲的任務(wù)具體開始的時間,就是依據(jù)前面任務(wù)的"結(jié)束時間"
4、周期性運行:timer.schedule(timertask task,date firsttime,long period) 從 firsttime 開始每隔 period 毫秒執(zhí)行一次任務(wù):
5、schedule(timertask task,long delay) 當前的時間為參考時間,在此時間基礎(chǔ)上延遲制定的毫秒數(shù)后執(zhí)行一次timertask任務(wù)。
6、schedule(timertask task,long delay,long period) 當前的時間為參考時間,在此基礎(chǔ)上延遲制定的毫秒數(shù),再以某一間隔時間無限次數(shù)地執(zhí)行某一任務(wù)。
7、timer的cancel() 和 timertask的cancel() 的區(qū)別?
前面提到任務(wù)的執(zhí)行是以對列的方式一個個被順序執(zhí)行的,timertask.cancel() 指的是 把當前任務(wù)從任務(wù)對列里取消。timer.cancel() 值的是把當前任務(wù)隊列里的所有任務(wù)都取消。值得注意的是,timer 的cancel()有時并不一定會停止執(zhí)行計劃任務(wù),而是正常執(zhí)行。這是因為timer類中的cancel()方法有時并沒有爭搶到queue鎖,所以timertask類中的任務(wù)繼續(xù)正常執(zhí)行。
三、scheduleatfixedrate(timertask task,date firsttime,long period) 和 schedule(timertask task,date firsttime,long period) 區(qū)別
相同點:
1、方法schedule 和方法 scheduleatfixedrate 都會按順序執(zhí)行,所以不用考慮非線程安全的情況。
2、方法schedule 和方法 scheduleatfixedrate 如果執(zhí)行任務(wù)的時間沒有被延遲,那么下一次任務(wù)的執(zhí)行時間參考的是上一次的任務(wù)的"開始"時的時間來計算的。
3、方法schedule 和方法 scheduleatfixedrate 如果執(zhí)行任務(wù)的時間被延遲了,那么下一次任務(wù)的執(zhí)行時間參考的是上一次任務(wù)"結(jié)束"時的時間來計算。
不同點:
方法schedule 和方法 scheduleatfixedrate 在使用上基本沒什么差別,就是 scheduleatfixedrate 具有追趕執(zhí)行性,什么意思呢?就是如果任務(wù) 在周期性運行過程中被打斷了,scheduleatfixedrate 會嘗試把之前落下的任務(wù)補上運行。而schedule就不管了,接著運行接下來的任務(wù)就行了,可以參考這篇博客,寫的很生動。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/jmcui/p/7519759.html