Java Timer、TimerTask、Reminder 类教程带示例
已发表: 2021-02-04
java.util.Timer
是一个实用程序类,可用于安排线程在未来某个时间执行。 Java Timer 类可用于安排任务运行一次或定期运行。
java.util.TimerTask
是一个实现 Runnable 接口的抽象类,我们需要扩展这个类来创建我们自己的 TimerTask,可以使用java Timer类进行调度。
Timer 类是线程安全的,多个线程可以共享一个 Timer 对象而无需外部同步。 Timer 类使用 java.util.TaskQueue 以给定的定期间隔添加任务,并且在任何时候都只能有一个线程运行 TimerTask,例如,如果您要创建一个 Timer 以每 10 秒运行一次但单线程执行需要 20 秒,然后 Timer 对象将继续向队列中添加任务,一旦一个线程完成,它将通知队列,另一个线程将开始执行。

Timer 类使用对象等待和通知方法来安排任务。 TimerTask 是一个abstract class
,我们继承它来提供具体的实现。 TimerTask 类implements
了Runnable
interface
,因此它是一个线程,因此您的 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 . . ! |
默认情况下,只要计时器线程在运行,程序就会一直运行。 您可以通过四种方式终止计时器线程:

- 在计时器上调用
cancel
。 您可以从程序中的任何位置执行此操作,例如从计时器任务的run
方法。 - 通过像这样创建计时器,使计时器的线程成为“守护进程”:
new Timer(true)
。 如果程序中剩下的唯一线程是守护线程,则程序退出。 - 在所有计时器的计划任务执行完毕后,删除对
Timer
对象的所有引用。 最终,计时器的线程将终止。 - 调用
System.exit
方法,使整个程序(及其所有线程)退出。