更新時間:2022-05-17 11:09:25 來源:動力節點 瀏覽2541次
一些java應用程序需要在一個固定的時間間隔之間執行一個方法。例如 GUI 應用程序應該從數據庫中更新一些信息。
對于這個功能,
您應該創建一個擴展 TimerTask 的類(在java.util包中可用)。TimerTask 是一個抽象類。
run()在您希望定期執行的公共 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
}
}
在調度程序任務之上運行的類。
實例化定時器對象Timer time = new Timer();
實例化計劃任務類對象ScheduledTask st = new ScheduledTask();
Timer.shedule()通過方法分配計劃任務。
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
以上就是關于“Java定時執行任務的步驟”介紹,大家如果想了解更多相關知識,不妨來關注一下動力節點的Java在線學習,里面的課程內容從入門到精通,細致全面,通俗易懂,適合小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習