首頁 > Java > java教程 > Java 中的定時器

Java 中的定時器

PHPz
發布: 2024-08-30 15:53:07
原創
454 人瀏覽過

Java 中的定時器可在 java 中使用。 util 套件擴展了 Object 類別並實作了 Serialized 和 Cloneable 介面。計時器類別包含用於執行與計時相關的活動的方法。 Java中的Timer類別用於執行與時間相關的任務調度。 Java 執行緒使用 Timer 類別的方法來排程任務,例如在某個時刻後執行一段程式碼,在某個預先定義的時間後重複執行程式碼。每個 Timer 物件都綁定到一個單獨的後台運行線程,該線程負責執行與該線程關聯的所有任務。要注意的是,java中的定時器類別是執行緒安全的;也就是說,在某一時刻,只有一個執行緒可以執行Timer類別的方法。 Timer 類別也使用二進位堆作為底層資料結構來儲存任務。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

Java 中定時器的語法

這是在 java 中如何使用 Timer 類別的基本語法:

文法:

// create a class extending TimerTask
class TimerHelper extends TimerTask
{
//define run method
public void run()
{
// Write Code to be executed by Timer
}
}
class MainClass{
public static void main(String[] args)
{
//create timer instance
Timer timer = new Timer();
// create Timer class instance
TimerTask task = new TimerHelper ();
// call timer method
timer.schedule(task, 3000,6000);
//first argument is timer object
// second argument is time in milliseconds after which the code will be first executed
// Third argument is time in milliseconds after which the code will be executed regularly.
}
}
登入後複製

上述語法的解釋:該語法展示如何在java中使用Timer類別。使用計時器類別涉及建立一個擴展 TimerTask 的類別並在其中定義 run 方法。 run 方法包含需要在時間驅動的基礎上執行的邏輯。以下是 Timer 類別聲明:

public  class Timer extends Object
implements Serializable, Cloneable
登入後複製

Java中Timer類別的方法

現在我們將看到 java Timer 類別中可用的不同方法和欄位。以下是 Timer 類別中常用方法的列表:

Method Name Description
public void schedule(TimerTask task, Date date) Schedules a task to be executed on the defined date.
public  void schedule (TimerTask task, Date firstTime, long timeperiod) The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
public  int purge() Used for removing all canceled tasks from the timer’s queue.
public void cancel() Cancel’s the timer.
public void schedule(TimeTask task, long delay) Schedules the task to be executed after the specified time in milliseconds.
public void schedule(TimeTask task, long delay, long period) The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
public  void scheduleAtFixedRate(TimerTask task, Date firstTime, long timeperiod) The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which the task will be executed regularly.
public void scheduleAtFixedRate (TimeTask task, long delay, long period) The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
方法名稱 描述 public void 計畫(TimerTask 任務,Date 日期) 安排任務在定義的日期執行。 公共無效計畫(TimerTask 任務、日期firstTime、長時間段) 第一個參數是要執行的TimerTask;第二個參數是第一次執行任務的時間,第三個參數是秒(以毫秒為單位),之後任務將定期執行。 public int purge() 用於從計時器佇列中刪除所有已取消的任務。 公共無效取消() 取消計時器。 public void Schedule(TimeTask任務,延遲較長) 安排任務在指定時間(以毫秒為單位)後執行。 公共無效日程(TimeTask任務,長延遲,長週期) 第一個參數是要執行的TimerTask;第二個參數是第一次執行任務的時間(以毫秒為單位),第三個參數是定期執行任務的秒數(以毫秒為單位)。 public  void ScheduleAtFixedRate(TimerTask 任務,日期firstTime,長時間段)​​td> 第一個參數是要執行的TimerTask;第二個參數是第一次執行任務的時間,第三個參數是秒(以毫秒為單位),之後定期執行任務。 public void ScheduleAtFixedRate(TimeTask任務,長延遲,長週期) 第一個參數是要執行的TimerTask;第二個參數是第一次執行任務的時間(以毫秒為單位),第三個參數是定期執行任務的秒數(以毫秒為單位)。 表>

From the above-stated methods, we have found two methods that are similar in working but different in the name; they are schedule and scheduleAtFixedRate. The difference between the two is that in the case of fixed-rate execution, each execution is scheduled in accordance with the initial execution. If there is a delay in execution, then two or more executions will occur in quick succession to overcome the delay.

Constructors in Timer Class

The timer class contains four constructors for instantiating timer object.

  • Timer(): Creates a new Timer Object.
  • Timer(boolean isDaemon): Creates a timer object with a corresponding thread specified to run as a daemon.
  • Timer(String name): Creates a timer object with a corresponding thread name.
  • Timer(String name, boolean isDaemon): This method is a combination of the above two constructors.

One of the above four listed constructors can be called depending on our requirements.

Examples of Implementing Timer in Java

Below is the example of Timer in Java:

Example #1

To start things, let us see a basic example of Timer class. In this example, we will demonstrate the use of the schedule method of the Timer class.

Code:

package com.edubca.timer;
import java.util.Timer;
import java.util.TimerTask;
class TimerHelper extends TimerTask
{
public static int counter = 0;
public void run()
{
counter++;
System.out.println("Timer run Number " + counter);
}
}
public class Main
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask timerhelper = new TimerHelper();
timer.schedule(timerhelper, 3000, 2000);
}
}
登入後複製

Explanation of the above code: The above code will execute the run method for the first time after 3 seconds as the first argument is 3000, and after every 2 seconds, the run method will be executed regularly. Here is the output that will be displayed:

Output:

Java 中的定時器

Example #2

In this example, we will see how to terminate a timer thread after a given number of timer runs.

Code:

package com.edubca.timer;
import java.util.Timer;
import java.util.TimerTask;
class TimerHelper extends TimerTask
{
public static int counter = 0;
public void run()
{
counter++;
if(counter ==3){
this.cancel();
System.out.println("Now Cancelling Thread!!!!!");
return;
}
System.out.println("Timer run Number " + counter);
}
}
public class Demo
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask helper = new TimerHelper();
helper.schedule(task, 3000, 2000);
}
}
登入後複製

In the above example, the timer will cancel after the three times run method is called using the timer class’s cancel method.

Output:

Java 中的定時器

以上是Java 中的定時器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板