如何在 运行 时将 TimerTask 提交给另一个 Timer

How to submit a TimerTask to another Timer when it 's running

在 TimerTask 对象的 run 方法中,如何将 timerTask 本身提交给另一个 Timer。 当timerTask为运行时,我应该做一个判断,决定它是否可以做一些工作。如果不满足条件,我应该取消它并把它放到另一个定时器。 我的 TimerTask 的代码是这样的:

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

有用吗?

您应该只使用一个 Timer,然后从外部监控条件,例如从 ThreadRunnable 或另一个 Timer。然后根据需要从外部监视器停止、取消、重新分配、启动计时器。


这是一个TimerTask

public class OurTask extends TimerTask {
    @Override
    public void run() {
        // Do something
    }
}

这是显示器:

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);
        }
    }
}

请注意,实际上您的 Monitor 也应该能够从外部取消,目前它会无限运行。

你可以这样称呼它:

Timer timer = new Timer();
timer.schedule(new OurTask(), ...);

Thread monitorThread = new Thread(new Monitor(timer));
monitorThread.start();

另请注意,与其使用 RunnableTimerThread,不如看看新的 Java 8 东西,尤其是接口 Future 和 类 实现它。