Temporizador de Java, TimerTask, tutorial de clase de recordatorio con ejemplo
Publicado: 2021-02-04
java.util.Timer
es una clase de utilidad que se puede usar para programar un subproceso para que se ejecute en un momento determinado en el futuro. La clase Java Timer se puede utilizar para programar una tarea para que se ejecute una sola vez o se ejecute a intervalos regulares.
java.util.TimerTask
es una clase abstracta que implementa la interfaz Runnable y necesitamos extender esta clase para crear nuestra propia TimerTask que se puede programar usando la clase Java Timer .
La clase Timer es segura para subprocesos y varios subprocesos pueden compartir un solo objeto Timer sin necesidad de sincronización externa. La clase de temporizador usa java.util.TaskQueue para agregar tareas en un intervalo regular dado y en cualquier momento solo puede haber un subproceso ejecutando TimerTask, por ejemplo, si está creando un temporizador para ejecutarse cada 10 segundos pero la ejecución de un solo subproceso tarda 20 segundos, luego, el objeto Timer seguirá agregando tareas a la cola y, tan pronto como finalice un subproceso, notificará a la cola y otro subproceso comenzará a ejecutarse.

La clase de temporizador utiliza métodos de notificación y espera de objeto para programar las tareas. TimerTask es una abstract class
y la heredamos para proporcionar una implementación concreta. La clase TimerTask implements
la interface
Runnable
, por lo que es un hilo y, por lo tanto, su implementación de TimerTask también es un hilo.
Ejemplo muy simple de Timer y TimerTask: la tarea se ejecuta una vez que han pasado 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" ) ; } } |
Resultado:
1 2 |
Task scheduled . . Now wait for 5 sec to see next message . . Time ' s up ! |
Este sencillo programa ilustra las siguientes partes básicas de la implementación y programación de una tarea para ser ejecutada por un subproceso de temporizador:
- Implemente una subclase personalizada de
TimerTask
. El métodorun
contiene el código que realiza la tarea. En este ejemplo, la subclase se llama CrunchifyReminder. - Cree un hilo instanciando la clase
Timer
. - Crea una instancia del objeto
TimerTask
(new CrunchifyReminder()
). - Programe la tarea del temporizador para su ejecución.
¿Cómo puedo realizar esta TimerTask repetidamente?
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" ) ; } } |
Resultado:
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 . . ! |
De forma predeterminada, un programa continúa ejecutándose mientras se ejecutan sus subprocesos de temporizador. Puede terminar un subproceso de temporizador de cuatro maneras:

- Invoque
cancel
en el temporizador. Puede hacer esto desde cualquier parte del programa, como desde el método derun
de una tarea de temporizador. - Haga que el subproceso del temporizador sea un "demonio" creando el temporizador de esta manera:
new Timer(true)
. Si los únicos subprocesos que quedan en el programa son subprocesos daemon, el programa se cierra. - Después de que todas las tareas programadas del temporizador hayan terminado de ejecutarse, elimine todas las referencias al objeto
Timer
. Eventualmente, el hilo del temporizador terminará. - Invoque el método
System.exit
, que hace que todo el programa (y todos sus subprocesos) salga.