This requirement came up in my Android app, but it applies to Java in general. My app \"does something\" every few seconds. I have implemented this as follows (just relevant sni
This answer helped me do the job. Posting some code on how I achieved it. Of particular importance are startTask()
and setInterval()
.
public class PeriodicTask {
private volatile boolean running = true;
private volatile int interval = 5;
private final Object lockObj = new Object();
public void startTask() {
while (running) {
doSomething();
synchronized (lockObj) {
try{
lockObj.wait(interval * 1000);
} catch(InterruptedException e){
//Handle Exception
}
}
}
}
public void stopTask() {
this.running = false;
}
public void setInterval(int newInterval) {
synchronized (lockObj) {
this.interval = newInterval;
lockObj.notify();
}
}
}