更新時(shí)間:2022-05-17 11:09:25 來源:動力節(jié)點(diǎn) 瀏覽2523次
一些java應(yīng)用程序需要在一個固定的時(shí)間間隔之間執(zhí)行一個方法。例如 GUI 應(yīng)用程序應(yīng)該從數(shù)據(jù)庫中更新一些信息。
對于這個功能,
您應(yīng)該創(chuàng)建一個擴(kuò)展 TimerTask 的類(在java.util包中可用)。TimerTask 是一個抽象類。
run()在您希望定期執(zhí)行的公共 void 方法中編寫您的代碼。
在您的 Main 類中插入以下代碼。
import java.util.TimerTask;
import java.util.Date;
/**
*
* @author Dhinakaran P.
*/
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {
Date now; // to display current time
// Add your task here
public void run() {
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
在調(diào)度程序任務(wù)之上運(yùn)行的類。
實(shí)例化定時(shí)器對象Timer time = new Timer();
實(shí)例化計(jì)劃任務(wù)類對象ScheduledTask st = new ScheduledTask();
Timer.shedule()通過方法分配計(jì)劃任務(wù)。
import java.util.Timer;
/**
*
* @author Dhinakaran P.
*/
//Main class
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create Repetitively task for every 1 secs
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
輸出:
Execution in Main Thread....0
Time is :Tue Jun 19 14:21:42 IST 2012
Time is :Tue Jun 19 14:21:43 IST 2012
Execution in Main Thread....1
Time is :Tue Jun 19 14:21:44 IST 2012
Time is :Tue Jun 19 14:21:45 IST 2012
Execution in Main Thread....2
Time is :Tue Jun 19 14:21:46 IST 2012
Time is :Tue Jun 19 14:21:47 IST 2012
Execution in Main Thread....3
Time is :Tue Jun 19 14:21:48 IST 2012
Time is :Tue Jun 19 14:21:49 IST 2012
Execution in Main Thread....4
Time is :Tue Jun 19 14:21:50 IST 2012
Time is :Tue Jun 19 14:21:51 IST 2012
Application Terminates
Time is :Tue Jun 19 14:21:52 IST 2012
以上就是關(guān)于“Java定時(shí)執(zhí)行任務(wù)的步驟”介紹,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下動力節(jié)點(diǎn)的Java在線學(xué)習(xí),里面的課程內(nèi)容從入門到精通,細(xì)致全面,通俗易懂,適合小白學(xué)習(xí),希望對大家能夠有所幫助。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743