Google | Onsite | Timer
11129

Given the following class with 2 methods

class MySystem {
    
    /**
     * Waits durationMillis milliseconds then runs the callback.
     *
     * Only one timer can be pending at one time. If called again before the
     * duration expires, the original timer is overwritten without running
     * callback.
    */
    static void setTimer(long durationMillis, Runnable callback);

    /** Returns the current time in milliseconds since system boot. */
    static long getCurrentTimeMillis();
    
}

Use these methods to implement the 3rd method to support multiple timers:

/**
 * Waits durationMillis milliseconds then runs the callback.
 *
 * Supports multiple concurrent timers. Calling addTimer will not break
 * any previously started timers.
 */
void addTimer(long durationMillis, Runnable callback);

Usage is as follows:

MySystem sys = new MySystem(); 
sys.addTimer(100, runnable1); 
Thread.sleep(50);
sys.addTimer(100, runnable2);
Comments (15)