我有这个代码,它基本上为我的应用程序提供了一个自定义计时器。
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
public class SMSFirewallTimer {
private static Logger logger = Logger.getLogger(SMSFirewallTimer.class);
Timer timer;
String timerId;
public SMSFirewallTimer(int seconds, String string) {
timer = new Timer();
timerId = string;
logger.debug("SMSFirewallTimer: timer started for: "+seconds +"seconds");
timer.schedule(new Timeout(string), seconds*1000);
}
public void cancelTimer()
{
this.timer.cancel();
logger.debug("SMSFirewallTimer: Cancelling timer for : " + this.timerId);
}
class Timeout extends TimerTask {
private String string;
public Timeout(String string) {
this.string = string;
}
@Override
public void run() {
logger.debug("SMSFirewallTimer: Time's up! for: " + this.string );
timer.cancel(); //Terminate the timer thread
}
}
}
现在出现的问题是我想在isRunning()
中使用SMSFirewallTimer
方法,它会告诉我,如果计时器仍然在运行,那么它也应该记住超时。
如果我只是在这个类中声明一个布尔值为isTimer
,那么只有在我们使用cancelTimer()
时它才有用,但它不会知道计时器是否过期,因为它是另一个调度方法{{1} }。
答案 0 :(得分:1)
试试这个
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
public class SMSFirewallTimer {
private static Logger logger = Logger.getLogger(SMSFirewallTimer.class);
Timer timer;
String timerId;
private Boolean isRunning;
public SMSFirewallTimer(int seconds, String string) {
timer = new Timer();
timerId = string;
logger.debug("SMSFirewallTimer: timer started for: "+seconds +"seconds");
isRunning = true;
timer.schedule(new Timeout(string), seconds*1000);
}
public void cancelTimer()
{
isRunning = false;
this.timer.cancel();
logger.debug("SMSFirewallTimer: Cancelling timer for : " + this.timerId);
}
public boolean isRunning() {
return isRunning;
}
class Timeout extends TimerTask {
private String string;
public Timeout(String string) {
this.string = string;
}
@Override
public void run() {
logger.debug("SMSFirewallTimer: Time's up! for: " + this.string );
isRunning = false;
timer.cancel(); //Terminate the timer thread
}
}
}
如果您不希望从Timeout访问SMSFirewallTimer isRunning字段,也可以保留Timeout的参考。
答案 1 :(得分:1)
Timeout
是SMSFirewallTimer
的内部类,这意味着SMSFirewallTimer
的每个实例都绑定到SMSFirewallTimer
的特定实例,并且可以访问其字段和方法
替换:
应该足够了 timer.cancel(); //Terminate the timer thread
带
cancelTimer(); //Terminate the timer thread
run
Timeout
方法中的。