What is the easiest way to have a piece of Java code scheduled at a given rate ?
Learn to cancel a task submitted to an executor service if the task still has to be executed and/or has not been completed yet. We can use the cancel() method of Future object that allows making the cancellation requests.
wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.
In Java 5+ with a ScheduledExecutorService
:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new Runnable() { @Override public void run() { // do stuff } }, 0, 5, TimeUnit.SECONDS);
The above method is favoured. Prior to Java 5 you used Timer
and TimerTask
:
timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // do staff } }, 0, 5000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With