How to check if X seconds has passed in Java?

13,160

Solution 1

For this simple check I would advise to simply use the timestamp (in milliseconds) instead of using java.util.Date or some other classes:

long test = System.currentTimeMillis();
if(test >= (pastTime + 15*1000)) { //multiply by 1000 to get milliseconds
  doSomething();
}

Please note that the pastTime variable would also have to be in milliseconds.

Unfortunately, there are no suitable "built-in" java classes to deal with time spans. In order to do this, check out the Joda Time library.

UPDATE: Java 8 introduced the java.time package, use that instead of the external joda time.

Solution 2

The java time library since JDK8 can do something like:

import java.time.Duration
import java.time.Instant

class MyTimeClass {
    
    public static void main(String[] args) {
        Instant then = Instant.now();
        Duration threshold = Duration.ofSeconds(3);
        // allow 5 seconds to pass
        Thread.sleep(5000);        
        assert timeHasElapsedSince(then, threshold) == true;
    }

    public static boolean timeHasElapsedSince(Instant then, Duration threshold) {
        return Duration.between(then, Instant.now()).toSeconds() > threshold.toSeconds();
    }
}

Solution 3

In my opinion you can put it in a while cycle. I would implement it in this way.

long initTime = System.currentTimeMillis();
boolean timeElapsed = false;
while(timeElapsed){
  if(System.currentTimeMillis - initTime > 15000 ){
    timeElapsed = true
  }else{
    doSomethingElse();
    Thread.sleep(500)
  }
}
doSomething()
Share:
13,160
Alex Hope O'Connor
Author by

Alex Hope O'Connor

Software Engineer working for DSITIA in Brisbane Australia.

Updated on June 25, 2022

Comments

  • Alex Hope O'Connor
    Alex Hope O'Connor almost 2 years

    I know in .NET I can do this:

    DateTime test = DateTime.Now;
    if (test >= (pastTime + TimeSpan.FromSeconds(15)) {
        doSomething();
    }
    

    What is the Java equivalent?

  • f1sh
    f1sh over 12 years
    Alex's code does to wait until the 15 seconds are over, it only checks if they are over. Misunderstood this as well when I first read it.
  • Maverik
    Maverik over 12 years
    @f1sh Yeah it's true...but usually when you check if an amount of time is over you will redo it until this time is really over...I don't see use cases for checking it only one time. But of corse, this is my opinion ;)
  • Alex Hope O'Connor
    Alex Hope O'Connor over 12 years
    Its not checked only one time, it is checked a number of times but other actions are performed based on this check during the interim.
  • Maverik
    Maverik over 12 years
    @Alex Yes, you are true...and that's what I mean for doSomethingElse() ;)
  • Jason Slobotski
    Jason Slobotski over 3 years
    Expanded on this accepted answer's edit about the java.time package in Java 8 in my answer below.