Create a Timer Using the Static Sleep() Method

Create a Timer Using the Static Sleep() Method

The simplest way to create a timer in Java is to use the static sleep() method on the Thread class. This code shows a main class that has a while loop for implementing the timer. The argument read in on Line 5 is used to set the interval for the timer. On Line 9, the program sleeps for “timeout” milliseconds. When the code gets out of the sleep() call, it increments the count on Line 15 and prints out a message on Line 16 that indicates the expiration of the timeout.

 1. public class MyTimer {2.   public static void main (String[] args) {3.   int count = 0;4. 5.   long timeout = Integer.parseInt(args[0]);6. 7.   while (true) {8.     try {9.       Thread.sleep(timeout);10.  }11.  catch (InterruptedException ie) {12.    ie.printStackTrace();13.  }14. 15.  count++;16.  System.out.println("Alarm #" + count + "::" +17.                      (count*timeout/1000) + " seconds elapsed");18. 19. }


Share the Post: