You should only use one Timer
and then monitor the condition from external, for example from a Thread
, a Runnable
or another Timer
. Then stop, cancel, re-assign, start the timer as necessary from your external monitor.
Here's a TimerTask
:
public class OurTask extends TimerTask {
@Override
public void run() {
// Do something
}
}
And here's the monitor:
public Monitor implements Runnable() {
private Timer mTimerToMonitor;
public Monitor(Timer timerToMonitor) {
this.mTimerToMonitor = timerToMonitor;
}
@Override
public void run() {
while (true) {
if (!flag) {
// Cancel the timer and start a new
this.mTimerToMonitor.cancel();
this.mTimerToMonitor = new Timer();
this.mTimerToMonitor.schedule(...);
}
// Wait a second
Thread.sleep(1000);
}
}
}
Note that in practice your Monitor
should also be able to get canceled from outside, currently it runs infinitely.
And this is how you could call it:
Timer timer = new Timer();
timer.schedule(new OurTask(), ...);
Thread monitorThread = new Thread(new Monitor(timer));
monitorThread.start();
Also note that instead of using Runnable
, Timer
and Thread
it could be worth taking a look into the new Java 8 stuff, especially the interface Future and classes implementing it.