devxlogo

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. }
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist