具有超时功能的 Java 计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15612753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:15:53  来源:igfitidea点击:

Java Timer with timeout capability

javatimer

提问by Sunny

I am implementing a timer:

我正在实现一个计时器:

timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //Do something;
                }
            },1000,1000);

But, I would like to have a timeout so that after lets say 100 tries/ 10 seconds, the timer stops automatically.

但是,我想要超时,以便在 100 次尝试/10 秒后,计时器自动停止。

Thanks.

谢谢。

回答by Evgeniy Dorofeev

try

尝试

    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        int n = 0;
        @Override
        public void run() {
            System.out.println(n);
            if (++n == 5) {
                timer.cancel();
            }
        }
    },1000,1000);

回答by Rob

You can simply have a variable outside the run method that keeps count of the iteration. Make an ifstatement inside the run()method that cancels the timer when it hits your desired amount. Increase the variable by one everytime the run()method executes.

您可以简单地在 run 方法之外使用一个变量来保持迭代计数。做一个if内部的语句run()是取消定时器,当它击中你的所需量的方法。每次run()方法执行时将变量加一。

回答by Ankit

start another timer, as soon as above timer starts, which cancels the above timer after 10sec. check to code below as a quick solution. but better you cancel the task() instead of timer.

启动另一个计时器,一旦上述计时器启动,就会在 10 秒后取消上述计时器。检查下面的代码作为快速解决方案。但最好取消 task() 而不是 timer。

timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    timer2.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        timer1.cancel();
                    }
            },0);
                    //Do something;
                }
            },1000,1000);

timer2 = new Timer();

回答by Ankur Shanbhag

I dont think we have java API for this in Timer class. You need to do it programmatically by implementing some custom logic based on your requirement.

我认为我们在 Timer 类中没有为此提供 Java API。您需要通过根据您的要求实现一些自定义逻辑来以编程方式执行此操作。