[英]How to cancel an already scheduled TimerTask?
我有一個小問題,似乎做對了。 我在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();
}
}
}
此類將確保除非可用方法至少返回Treshold,否則我們的應用程序將不會開始處理SocketInputStream。 但是問題是,一旦我將DoWaitTask與Timer計划在一起,它將永久運行。 通過取消計時器,任務仍然運行,整個應用程序掛起,但是更重要的是,一旦已處理並關閉流,它將嘗試在流上調用available。 當然,這會導致一個不錯的IOException:流關閉。
如何與計時器一起停止計划的任務? timer.cancel顯然是不夠的。
此致喬伊
在計時器任務的run()方法中使用TimerTask.cancel() 。 根據Javadoc的方法:
請注意,從重復計時器任務的run方法中調用此方法絕對保證計時器任務不會再次運行。
私人計時器reportTimer = null;
if (reportTimer != null) {
reportTimer.cancel();
reportTimer = null;
}
reportTimer = new Timer();
reportTimer.schedule(new TimerTask() {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.