如何为此 class 实现 Timer Running()

How to implemet isTimerRunning() for this class

我有这段代码,它基本上为我的应用程序提供了一个自定义计时器。

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

现在问题出现了,我想要 SMSFirewallTimer 中的 isRunning() 方法,它将告诉我计时器是否仍然是 运行,并且它还应该保持超时介意。

如果我只是在这个 class 中将一个布尔值声明为 isTimer 它只在我们使用 cancelTimer() 时有效,但它不会知道计时器是否过期,因为它是另一个预定方法 new Timeout(string).

试试这个

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 的参考。

TimeoutSMSFirewallTimer 的内部 class 这意味着 SMSFirewallTimer 的每个实例都绑定到 SMSFirewallTimer 的特定实例,即可以访问其字段和方法。

应该足以替换:

        timer.cancel(); //Terminate the timer thread            

        cancelTimer(); //Terminate the timer thread            

Timeoutrun 方法中。