Search code examples
javastopwatch

Keeping track of currentTimeMillis


I need to create an object that will stop execution for a certain amount of time using its own class methods. How do I have a program keep track of passing time and execute a function when a specified amount of time has passed.

I imagine .......

long pause; //a variable storing pause length in milliseconds.............
long currentTime; // which store the time of execution of the pause ,............. 

and when another variable tracking time has the same value as currentTime + pause, the next line of code is executed. Is it possible to make a variable that for a short period changes every millisecond as time passes?


Solution

  • For a simple solution, you could just use Thread#sleep

    public void waitForExecution(long pause) throws InterruptedException { 
        // Perform some actions...
        Thread.sleep(pause);
        // Perform next set of actions
    }
    

    With a timer...

    public class TimerTest {
    
        public static void main(String[] args) {
            Timer timer = new Timer("Happy", false);
            timer.schedule(new TimerTask() {
    
                @Override
                public void run() {
                    System.out.println("Hello, I'm from the future!");
                }
            }, 5000);
    
            System.out.println("Hello, I'm from the present");
        }
    }
    

    And with a loop

    long startAt = System.currentTimeMillis();
    long pause = 5000;
    System.out.println(DateFormat.getTimeInstance().format(new Date()));
    while ((startAt + pause) > System.currentTimeMillis()) {
        // Waiting...
    }
    System.out.println(DateFormat.getTimeInstance().format(new Date()));
    

    Note, this is more expensive then the other two solutions as the loop continues to consume CPU cycles, where as the Thread#sleep and Timer use a internal scheduling mechanism that allows the threads to idle (and not consume cycles)