Javaのタイマー

PHPz
リリース: 2024-08-30 15:53:07
オリジナル
356 人が閲覧しました

Java のタイマーは Java で使用できます。 util パッケージは Object クラスを拡張し、Serializable および Cloneable インターフェイスを実装します。 timer クラスには、タイミング関連のアクティビティを実行するために使用されるメソッドが含まれています。 Java のタイマー クラスは、時間に関連したタスクのスケジューリングを実行するために使用されます。 Java スレッドは、Timer クラスのメソッドを使用して、ある瞬間の後にコードのセクションを実行したり、事前定義された時間の後にコードを繰り返し実行したりするなどのタスクをスケジュールします。各 Timer オブジェクトは、スレッドに関連付けられたすべてのタスクの実行を担当する個別のバックグラウンド実行スレッドにバインドされます。 Java のタイマー クラスはスレッドセーフであることに注意してください。つまり、一度に 1 つのスレッドだけが Timer クラス メソッドを実行できます。また、Timer クラスは、タスクを保存するための基礎となるデータ構造としてバイナリ ヒープを利用します。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

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 のタイマー クラスのメソッド

ここで、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.
メソッド名 説明 公開無効スケジュール(TimerTask タスク、日付 date) 定義された日に実行されるタスクをスケジュールします。 公開無効スケジュール (TimerTask タスク、初回日付、長期期間) 最初の引数は実行される TimerTask です。 2 番目の引数は、タスクが初めて実行されるまでの時間です。3 番目の引数は、その後タスクが定期的に実行されるまでの秒数 (ミリ秒) です。 public int purge() キャンセルされたすべてのタスクをタイマーのキューから削除するために使用されます。 public void cancel() キャンセルするとタイマーが終了します。 公開無効スケジュール (TimeTask タスク、長い遅延) ミリ秒単位で指定された時間の後にタスクが実行されるようにスケジュールします。 公開無効スケジュール (TimeTask タスク、長時間遅延、長期間) 最初の引数は実行される TimerTask です。 2 番目の引数は、タスクが初めて実行されるまでの時間 (ミリ秒) であり、3 番目の引数は、タスクが定期的に実行されるまでの秒数 (ミリ秒) です。 public voidScheduleAtFixedRate(TimerTask task, Date firstTime, long timeperiod) 最初の引数は実行される TimerTask です。 2 番目の引数は、タスクが初めて実行されるまでの時間です。3 番目の引数は、その後タスクが定期的に実行されるまでの秒数 (ミリ秒) です。 public voidScheduleAtFixedRate (TimeTask タスク、長い遅延、長い期間) 最初の引数は実行される TimerTask です。 2 番目の引数は、タスクが初めて実行されるまでの時間 (ミリ秒) であり、3 番目の引数は、タスクが定期的に実行されるまでの秒数 (ミリ秒) です。 テーブル>

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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!