timer和timertask是jdk自帶的定時任務實現,無需導入第三方jar包來完成
1、指定多久之后執行此任務,注意:只會執行一次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
Timer timer; public TimerTest( int time){ timer = new Timer(); timer.schedule( new timerTaskTest(),time* 1000 ); //timer.schedule(執行的方法,延遲多久執行(ms)) } public static void main(String[] args) { System.out.println( "timer begin..." ); new TimerTest( 3 ); } @Override public void run() { System.out.println( "time's up!!" ); } } } |
2、在指定的時間執行任務
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class TimerTest1 { Timer timer; public TimerTest1(){ Date time = getTime(); System.out.println( "指定時間time=" +time); timer = new Timer(); timer.schedule( new TimerTaskTest1(),time); //timer.schedule(執行的方法,要執行的時間) } public Date getTime(){ //設置執行時間 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, 5 ); calendar.set(Calendar.MINUTE, 46 ); calendar.set(Calendar.SECOND, 00 ); Date time = calendar.getTime(); return time; } public static void main(String[] args) { new TimerTest1(); } class TimerTaskTest1 extends TimerTask{ public void run() { System.out.println( "指定時間執行線程任務..." ); } } } |
3、在延遲指定時間后以指定的間隔時間循環執行定時任務
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class TimerTest2 { Timer timer; public TimerTest2(){ timer = new Timer(); timer.schedule( new TimerTaskTest2(), 1000 , 2000 ); //tiemr.schedule(執行的方法,延遲時間,多久執行一次) } class TimerTaskTest2 extends TimerTask{ @Override public void run() { System.out.println( "本次任務執行時間" + new Date()); } } public static void main(String[] args) { new TimerTest2(); } } |
到這里定時任務實現類已經完成,如果是web項目,則需要在web.xml中配置啟動
1
2
3
|
<listener> <listener- class >com.sxl.ContextListener</listener- class > </listener> |
配置完成即可。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。