/*--------------------------------------------------
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.com
* You are free to use/modify this source code.
*-------------------------------------------------*/

import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class Timer1 extends MIDlet implements CommandListener
{
  private Display display;
  private Form fmMain;
  private Command cmExit;
  private Command cmStop;      // Stop the timer
  private Timer tm;            // Timer
  private TestTimerTask tt;    // Task
  private int count = 0;       // How many times has task run

  public Timer1()
  {
    display = Display.getDisplay(this);
    fmMain = new Form("Timer Test");
    fmMain.append("waiting...\n");

    cmExit = new Command("Exit", Command.EXIT, 1);
    cmStop= new Command("Stop", Command.STOP, 2);
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmStop);
    fmMain.setCommandListener(this);


    // Create a timer that will go off in 5 seconds
    tm = new Timer();
    tt = new TestTimerTask();
    tm.schedule(tt,5000);


    // Create a timer that will go off in 5 seconds, repeating every 3 seconds
//    tm = new Timer();
//    tt = new TestTimerTask();
//    tm.schedule(tt,5000, 3000);

    // Create a timer that will go off in 5 seconds, repeating every 3 seconds
//    tm = new Timer();
//    tt = new TestTimerTask();
//    tm.scheduleAtFixedRate(tt,5000, 3000);

    // Create timer that starts at current date
//    tm = new Timer();
//    tt = new TestTimerTask();
//    tm.schedule(tt, new Date());

    // Create timer that starts at current date, repeating every 3 seconds
//    tm = new Timer();
//    tt = new TestTimerTask();
//    tm.schedule(tt, new Date(), 3000);

    // Create timer that starts at current date, repeating every 3 seconds
//    tm = new Timer();
//    tt = new TestTimerTask();
//    tm.scheduleAtFixedRate(tt, new Date(), 3000);
  }

  public void startApp ()
  {
    display.setCurrent(fmMain);
  }
  public void destroyApp (boolean unconditional) {}
  public void pauseApp () { }
  public void commandAction(Command c, Displayable d)
  {
    if (c == cmStop)
    {
      tm.cancel();
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
  }

  private class TestTimerTask extends TimerTask
  {
    public final void run()
    {
      fmMain.append("run count: " + ++count + "\n");
    }
  }
}

