简体   繁体   English

如何取消已经安排好的TimerTask?

[英]How to cancel an already scheduled TimerTask?

I have a tiny problem that I can't seem to do right. 我有一个小问题,似乎做对了。 I have the following class in java: 我在Java中有以下课程:

package pooledtcpconnector.utilities;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Notifier implements Runnable {

    private final ILogger logger;

    private Timer mTimer;
    private final int Treshold;
    private final InputStream ResponseStream;
    private final TimerTask DoWaitTask;

    public Notifier(final InputStream _ResponseStream, final Integer _Treshold, final ILogger logger) {
        this.logger = logger;

        mTimer = new Timer();

        this.ResponseStream = _ResponseStream;
        this.Treshold = _Treshold;

        DoWaitTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    int mSize = ResponseStream.available();
                    if (mSize >= Treshold) {
                        mTimer.cancel();
                    }
                } catch (final IOException ex) {
                    final String ExceptionMessage = ex.getMessage();
                    logger.LogMessage(
                            this.getClass().getCanonicalName(),
                            "Notifier.DoWaitTask:run.ResponseStream.available",
                            ex.getClass().getCanonicalName(),
                            new String[]{
                                ExceptionMessage,
                                "Parameters:",
                                String.format("-"),
                            });

                    Logger.getLogger(Notifier.class.getCanonicalName()).log(Level.FINE, ex.getMessage(), ex.getCause());
                }
            }
        };
    }

    @Override
    public void run() {
        synchronized (this) {
            mTimer.scheduleAtFixedRate(DoWaitTask, 250, 200);
            // Notification mechanism
            notify();
        }
    }

}

This class would ensure that our application won't start processing the SocketInputStream unless the available method returns at least Treshold. 此类将确保除非可用方法至少返回Treshold,否则我们的应用程序将不会开始处理SocketInputStream。 The problem however is that, once I schedule the DoWaitTask with the Timer it runs for eternity. 但是问题是,一旦我将DoWaitTask与Timer计划在一起,它将永久运行。 By cancelling the timer the task still runs and the whole application hangs, but more importantly it tries to call available on the stream once it already has been processed and closed. 通过取消计时器,任务仍然运行,整个应用程序挂起,但是更重要的是,一旦已处理并关闭流,它将尝试在流上调用available。 Of course this results in a nice IOException: stream closed. 当然,这会导致一个不错的IOException:流关闭。

How could I stop the scheduled task along with the timer? 如何与计时器一起停止计划的任务? timer.cancel obviously isn't enough. timer.cancel显然是不够的。

Regards, Joey 此致乔伊

Use TimerTask.cancel() from within your timer task's run() method. 在计时器任务的run()方法中使用TimerTask.cancel() According to the Javadoc for this method: 根据Javadoc的方法:

Note that calling this method from within the run method of a repeating timer task absolutely guarantees that the timer task will not run again. 请注意,从重复计时器任务的run方法中调用此方法绝对保证计时器任务不会再次运行。

private Timer reportTimer = null; 私人计时器reportTimer = null;

    if (reportTimer != null) {
        reportTimer.cancel();
        reportTimer = null;
    }

    reportTimer = new Timer();
    reportTimer.schedule(new TimerTask() {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM