Javaタイマー、TimerTask、リマインダークラスのチュートリアルと例
公開: 2021-02-04
java.util.Timer
は、将来の特定の時間に実行されるスレッドをスケジュールするために使用できるユーティリティクラスです。 Java Timerクラスを使用して、タスクを1回だけ実行するか、定期的に実行するようにスケジュールできます。
java.util.TimerTask
は、Runnableインターフェースを実装する抽象クラスであり、このクラスを拡張して、 javaTimerクラスを使用してスケジュールできる独自のTimerTaskを作成する必要があります。
タイマークラスはスレッドセーフであり、複数のスレッドが外部同期を必要とせずに単一のタイマーオブジェクトを共有できます。 Timerクラスはjava.util.TaskQueueを使用して、指定された一定の間隔でタスクを追加します。たとえば、10秒ごとに実行するTimerを作成しているが、シングルスレッドの実行に20秒かかる場合、TimerTaskを実行できるスレッドは常に1つだけです。その後、Timerオブジェクトはキューにタスクを追加し続け、1つのスレッドが終了するとすぐにキューに通知し、別のスレッドが実行を開始します。

Timerクラスは、Objectwaitメソッドとnotifyメソッドを使用してタスクをスケジュールします。 TimerTaskはabstract class
であり、具体的な実装を提供するためにそれを継承します。 TimerTaskクラスはRunnable
interface
をimplements
しているため、スレッドであるため、TimerTaskの実装もスレッドです。
非常に単純なTimerおよびTimerTaskの例:タスクは5 seconds
が経過すると実行されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com . crunchify . tutorials ; import java . util . Timer ; import java . util . TimerTask ; /** * Author: Crunchify.com */ public class CrunchifyTimerTaskExample { Timer timer ; public CrunchifyTimerTaskExample ( int seconds ) { timer = new Timer ( ) ; timer . schedule ( new CrunchifyReminder ( ) , seconds * 1000 ) ; } class CrunchifyReminder extends TimerTask { public void run ( ) { System . out . format ( "Timer Task Finished..!%n" ) ; timer . cancel ( ) ; // Terminate the timer thread } } public static void main ( String args [ ] ) { new CrunchifyTimerTaskExample ( 5 ) ; System . out . format ( "Task scheduled.. Now wait for 5 sec to see next message..%n" ) ; } } |
結果:
1 2 |
Task scheduled . . Now wait for 5 sec to see next message . . Time ' s up ! |
この単純なプログラムは、タイマースレッドによって実行されるタスクの実装とスケジューリングの次の基本的な部分を示しています。
-
TimerTask
のカスタムサブクラスを実装します。run
メソッドには、タスクを実行するコードが含まれています。 この例では、サブクラスの名前はCrunchifyReminderです。 -
Timer
クラスをインスタンス化してスレッドを作成します。 -
TimerTask
オブジェクトをインスタンス化します(new CrunchifyReminder()
)。 - タイマータスクを実行するようにスケジュールします。
このTimerTaskを繰り返し実行するにはどうすればよいですか?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package crunchify . com . tutorials ; import java . util . Timer ; import java . util . TimerTask ; import java . awt . Toolkit ; /** * Author: Crunchify.com * Java Timer and TimerTask - Reminder Class Tutorials */ public class CrunchifyTimerTaskExample { // Toolkit This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. // Subclasses of the Toolkit class are used to bind the various components to particular native toolkit implementations. Toolkit toolkit ; // Timer A facility for threads to schedule tasks for future execution in a background thread. // Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Timer timer ; public CrunchifyTimerTaskExample ( ) { toolkit = Toolkit . getDefaultToolkit ( ) ; timer = new Timer ( ) ; // schedule() Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. // Subsequent executions take place at approximately regular intervals separated by the specified period. timer . schedule ( new CrunchifyReminder ( ) , 0 , // initial delay 1 * 1000 ) ; // subsequent rate } // TimerTask A task that can be scheduled for one-time or repeated execution by a Timer. // A timer task is not reusable. Once a task has been scheduled for execution on a Timer or cancelled, // subsequent attempts to schedule it for execution will throw IllegalStateException. class CrunchifyReminder extends TimerTask { int loop = 5 ; public void run ( ) { if ( loop > 0 ) { // beep() Emits an audio beep depending on native system settings and hardware capabilities. toolkit . beep ( ) ; System . out . format ( "Knock Knock..!\n" ) ; loop -- ; } else { toolkit . beep ( ) ; System . out . format ( "\nThat's it.. Done..!" ) ; // cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, // its execution thread terminates gracefully, and no more tasks may be scheduled on it. timer . cancel ( ) ; } } } public static void main ( String args [ ] ) { new CrunchifyTimerTaskExample ( ) ; System . out . format ( "Task scheduled..!%n \n" ) ; } } |
結果:
1 2 3 4 5 6 7 8 9 |
Task scheduled . . ! Knock Knock . . ! Knock Knock . . ! Knock Knock . . ! Knock Knock . . ! Knock Knock . . ! That ' s it . . Done . . ! |
デフォルトでは、プログラムはタイマースレッドが実行されている限り実行を続けます。 タイマースレッドは、次の4つの方法で終了できます。

- タイマーで
cancel
を呼び出します。 これは、タイマータスクのrun
メソッドなど、プログラムのどこからでも実行できます。 -
new Timer(true)
のようにタイマーを作成して、タイマーのスレッドを「デーモン」にします。 プログラムに残っているスレッドがデーモンスレッドだけの場合、プログラムは終了します。 - タイマーのスケジュールされたすべてのタスクの実行が終了したら、
Timer
オブジェクトへのすべての参照を削除します。 最終的に、タイマーのスレッドは終了します。 -
System.exit
メソッドを呼び出します。これにより、プログラム全体(およびそのすべてのスレッド)が終了します。