A simple java program to simulate a stopwatch

Recently, I wrote a small java program to simulate a stopwatch count down by using java.util.Timer class method scheduleAtFixedRate(TimerTask task, long delay, long period) which schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

My program just simply count down from 1000 to 1 second by second roughly.

//Stopwatch

import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
  static int interval;
  static Timer timer;

  public static void main(String[] args) {

    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval =10000;
    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
         System.out.println(setInterval());
      }
    }, delay, period);
  }

  private static final int setInterval(){
    if( interval== 1) timer.cancel();
      return --interval;
  }
}

About henry416
I am a computer technology explorer and an university student based on Toronto. If you have any question, please feel free to discuss and comment here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s