Timer: come usarli in Java
Vediamo un semplice esempio di utilizzo dei Timer in Java e una midlet di esempio che ci fà vedere le “stelle”
Una caratteristica molto utile di Java è quella di poter schedulare delle cose da fare che vengono eseguiti in background in un thread. Anche la versione MIDP dispone di questi task che sono definiti nelle seguenti classi:
1 2 |
java.util.TimerTask java.util.Timer |
La classe TimerTask è una class astratta che viene utilizzata come classe base per tutti i task schedulati. La classe Task invece crea e amministra i thread sui quali i task sono eseguiti. Ecco un esempio :
1 2 3 4 5 6 7 |
import java.util.*; public class MyTask extends TimerTask { public void run() { System.out.println( "Running the task" ); } } |
Dopo aver creato questa classe (che assomiglia tanto ad un Thread, infatti TimerTask implementa l’interfaccia Runnable ) utilizziamola:
1 2 3 4 5 6 7 8 9 |
Timer timer = new Timer(); TimerTask task = new MyTask(); // aspetta 10 secondi prima dell'esecuzione timer.schedule( task, 10000 ); // aspetta 5 secondi prima dell'esecuzione,poi // viene eseguita ogni 10 secondi timer.schedule( task, 5000, 10000 ); |
Ogni oggetto timer crea e controlla un singolo thread. Di solito basta un singolo Timer per un applicazione ma potete usarne quanti ne volete per le più svariate cose. Potete anche fermare un Timer ad un certo punto tramite il suo metodo cancel.
Una volta fermato un timer non può essere riavviato. Bisogna quindi ricreare un nuovo oggetto e rischedularlo. Ecco quindi un esempio di MIDlet che fà uso dei Timer per creare un effetto grafico carino, delle stelle che si muovono.
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; public class TimerDemo extends MIDlet { Display display; StarField field = new StarField(); FieldMover mover = new FieldMover(); Timer timer = new Timer(); public TimerDemo() { display = Display.getDisplay( this ); } protected void destroyApp( boolean unconditional ) { } protected void startApp() { display.setCurrent( field ); timer.schedule( mover, 100, 100 ); } protected void pauseApp() { } public void exit(){ timer.cancel(); // stop destroyApp( true ); notifyDestroyed(); } class FieldMover extends TimerTask { public void run(){ field.scroll(); } } class StarField extends Canvas { int height; int width; int[] stars; Random generator = new Random(); boolean painting = false; public StarField(){ height = getHeight(); width = getWidth(); stars = new int[ height ]; for( int i = 0; i < height; ++i ){ stars[i] = -1; } } public void scroll() { if( painting ) return; for( int i = height-1; i > 0; --i ){ stars[i] = stars[i-1]; } stars[0] = ( generator.nextInt() % ( 3 * width ) ) / 2; if( stars[0] >= width ){ stars[0] = -1; } repaint(); } protected void paint( Graphics g ){ painting = true; g.setColor( 0, 0, 0 ); g.fillRect( 0, 0, width, height ); g.setColor( 255, 255, 255 ); for( int y = 0; y < height; ++y ){ int x = stars[y]; if( x == -1 ) continue; g.drawLine( x, y, x, y ); } painting = false; } protected void keyPressed( int keyCode ){ exit(); } } } |
Questa MIDlet utilizza Timer per schedulare l’esecuzione di una sottoclasse, FieldMover, ogni 100 millisecondi. Così facendo si ha la sensazione di stelle che si muovono. Buon divertimento