Tutorial Java Timer, TimerTask, Reminder Class con esempio
Pubblicato: 2021-02-04
java.util.Timer
è una classe di utilità che può essere utilizzata per pianificare un thread da eseguire in un determinato momento in futuro. La classe Java Timer può essere utilizzata per pianificare un'attività da eseguire una sola volta o da eseguire a intervalli regolari.
java.util.TimerTask
è una classe astratta che implementa l'interfaccia Runnable e abbiamo bisogno di estendere questa classe per creare il nostro TimerTask che può essere programmato usando la classe java Timer .
La classe Timer è thread-safe e più thread possono condividere un singolo oggetto Timer senza necessità di sincronizzazione esterna. La classe Timer utilizza java.util.TaskQueue per aggiungere attività a un determinato intervallo regolare e in qualsiasi momento può esserci un solo thread che esegue TimerTask, ad esempio se stai creando un timer da eseguire ogni 10 secondi ma l'esecuzione di un singolo thread richiede 20 secondi, quindi l'oggetto Timer continuerà ad aggiungere attività alla coda e non appena un thread è terminato, avviserà la coda e un altro thread inizierà l'esecuzione.

La classe Timer utilizza i metodi di attesa e notifica dell'oggetto per pianificare le attività. TimerTask è una abstract class
e la ereditiamo per fornire un'implementazione concreta. La classe TimerTask implements
interface
Runnable
quindi è un thread e quindi anche l'implementazione di TimerTask è un thread.
Esempio molto semplice di Timer e TimerTask: l'attività viene eseguita una volta trascorsi 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" ) ; } } |
Risultato:
1 2 |
Task scheduled . . Now wait for 5 sec to see next message . . Time ' s up ! |
Questo semplice programma illustra le seguenti parti di base dell'implementazione e della pianificazione di un'attività da eseguire da un thread timer:
- Implementa una sottoclasse personalizzata di
TimerTask
. Il metodorun
contiene il codice che esegue l'attività. In questo esempio, la sottoclasse è denominata CrunchifyReminder. - Crea un thread istanziando la classe
Timer
. - Crea un'istanza dell'oggetto
TimerTask
(new CrunchifyReminder()
). - Pianificare l'attività timer per l'esecuzione.
Come posso eseguire questo TimerTask ripetutamente?
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" ) ; } } |
Risultato:
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 . . ! |
Per impostazione predefinita, un programma continua a funzionare finché i thread del timer sono in esecuzione. Puoi terminare un thread timer in quattro modi:

- Richiama l'
cancel
sul timer. Puoi farlo da qualsiasi punto del programma, ad esempio dal metodo dirun
di un'attività timer. - Rendi il thread del timer un "demone" creando il timer in questo modo:
new Timer(true)
. Se gli unici thread rimasti nel programma sono thread daemon, il programma esce. - Al termine dell'esecuzione di tutte le attività pianificate del timer, rimuovere tutti i riferimenti all'oggetto
Timer
. Alla fine, il thread del timer terminerà. - Richiamare il metodo
System.exit
, che fa uscire l'intero programma (e tutti i suoi thread).