Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Beginner
Jul 7, 1999



Application Security Testing: An Integral Part of DevOps

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;
5.   long timeout = Integer.parseInt(args[0]);
7.   while (true) {
8.     try {
9.       Thread.sleep(timeout);
10.  }
11.  catch (InterruptedException ie) {
12.    ie.printStackTrace();
13.  }
15.  count++;
16.  System.out.println("Alarm #" + count + "::" +
17.                      (count*timeout/1000) + " seconds elapsed");
19. }
Ajit Sagar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date