2

In a run method of a TimerTask object, How can I submit the timerTask itself to another Timer. When the timerTask is running, I should do a judge and decide whether it can do some work. If it not meet the condition, I should cancel it and put it to another Timer. Code of my TimerTask is like this:

@Override
public void run() {
    try {
        if (flag) {
           // do something
        } else {
           new Timer().schedule(this, 1000 * 60);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Will it work?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
zaihui
  • 53
  • 1
  • 9
  • 1
    Posting some code would help – Kovalainen Oct 31 '17 at 13:58
  • 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. – Zabuzard Oct 31 '17 at 14:16

1 Answers1

1

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.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82