検索

Javaのタイマー

Aug 30, 2024 pm 03:53 PM
java

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

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?Mar 17, 2025 pm 05:46 PM

この記事では、Javaプロジェクト管理、自動化の構築、依存関係の解像度にMavenとGradleを使用して、アプローチと最適化戦略を比較して説明します。

適切なバージョン化と依存関係管理を備えたカスタムJavaライブラリ(JARファイル)を作成および使用するにはどうすればよいですか?適切なバージョン化と依存関係管理を備えたカスタムJavaライブラリ(JARファイル)を作成および使用するにはどうすればよいですか?Mar 17, 2025 pm 05:45 PM

この記事では、MavenやGradleなどのツールを使用して、適切なバージョン化と依存関係管理を使用して、カスタムJavaライブラリ(JARファイル)の作成と使用について説明します。

カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?Mar 17, 2025 pm 05:44 PM

この記事では、カフェインとグアバキャッシュを使用してJavaでマルチレベルキャッシュを実装してアプリケーションのパフォーマンスを向上させています。セットアップ、統合、パフォーマンスの利点をカバーし、構成と立ち退きポリシー管理Best Pra

キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPA(Java Persistence API)を使用するにはどうすればよいですか?キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPA(Java Persistence API)を使用するにはどうすればよいですか?Mar 17, 2025 pm 05:43 PM

この記事では、キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPAを使用することについて説明します。潜在的な落とし穴を強調しながら、パフォーマンスを最適化するためのセットアップ、エンティティマッピング、およびベストプラクティスをカバーしています。[159文字]

Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Mar 17, 2025 pm 05:35 PM

Javaのクラスロードには、ブートストラップ、拡張機能、およびアプリケーションクラスローダーを備えた階層システムを使用して、クラスの読み込み、リンク、および初期化が含まれます。親の委任モデルは、コアクラスが最初にロードされ、カスタムクラスのLOAに影響を与えることを保証します

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。