Search code examples
javaeventsexecution

How can i execute code for a specific amount of time in java?


I'd like to execute some code for, let's say 5 seconds, inside of a method that listens for events. I've tried to use Threads but wasn't able to make it work properly.

This is my code for now, it's just a listener that triggers when a message with the string in the if statement is detected:

if (message != null){
            if (message.equalsIgnoreCase("w")){

            }
        }

this check is ran every second so i don't know if "while" statements could work


Solution

  • A trivial approach would be to simply execute your code in a loop and check in each iteration whether your timing-threshold was reached, such as:

    // necessary imports for using classes Instant and Duration.
    import java.time.Instant;
    import java.time.Duration;
    
    // ...
    
    // start time point of your code execution.
    Instant start = Instant.now();
    
    // targeted duration of your code execution (e.g. 5 sec.).
    Duration duration = Duration.ofSeconds(5);
         
    // loop your code execution and test in each iteration whether you reached your duration threshold.
    while (Duration.between(start, Instant.now()).toMillis() <= duration.toMillis())
    {
        // execute your code here ...
    }