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.
CodePudding user response:
Just an idea not for deployment but should give you an starting point
//record start time
long start=System.currentTimeMillis();
//keep running until 5000ms[5s] have
//elapsed since the start
while(System.currentTimeMillis()-start<=5000)
{
//Do some stuff here
}
If your event handler is executed in the same thread as your system then this will block your system for 5 seconds and stop it from handling other events during that duration.
So its better to dispatch your events to seperate threads or execute the above logic in a seperate thread
CodePudding user response:
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 ...
}