设置定时器超时 - 新的Timer()失败后,取消和清除 [英] Setting a Timer for a timeout - new Timer() fails after cancel and purge

查看:755
本文介绍了设置定时器超时 - 新的Timer()失败后,取消和清除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些位置发现code和,而我在等一个合适的精度读我也想有一个超时和使用任何的最佳位置是读取到这一点。

我似乎被误解如何取消并重新启动一个定时器。

我想,当我开始我的搜索启动超时定时器并重启定时器每次我重复我的搜索时间...

 私人无效refreshLocation(){
    如果(locationTimeoutTimer!= NULL){
        locationTimeoutTimer.cancel();
        locationTimeoutTimer.purge();
    }    locationTimeoutTimer =新的Timer();
    locationTimeoutTimer.schedule(timeoutReached,60000);
        //做其他事情...
}

不过,我得到以下错误每当这个refreshLocation被称为第二次。

  java.lang.IllegalStateException:TimerTask的已安排


解决方案

您code非常相似,code我有 - 那就是工作。但一些分歧,我注意到是


  • 您可能需要创建新的计时器作为命名守护程序 - 例如 locationTimer =新的Timer(locationtimer,真正的);

  • 您可能需要创建一个新的TimerTask每次安排的时间(我假设timeoutReached是TimerTask的?) - 例如 locationTimer.schedule(新timeoutReached(),60000);

I have some location finding code and while I'm waiting for a read of an appropriate accuracy I'd also like to have a timeout and use whatever the best location read is up to that point.

I seem to be misunderstanding how to cancel and restart a timer.

I want to start a timeout timer when I begin my search and restart the timer every time I repeat my search...

private void refreshLocation() {
    if (locationTimeoutTimer != null) {
        locationTimeoutTimer.cancel();
        locationTimeoutTimer.purge();
    }

    locationTimeoutTimer = new Timer();
    locationTimeoutTimer.schedule(timeoutReached, 60000);
        //Do other things...
}

However, I get the following error whenever this refreshLocation is called a second time.

java.lang.IllegalStateException: TimerTask is scheduled already

解决方案

Your code is very similar to code I have - that is working. But some differences I notice are that

  • you may need to create the new timer as a named daemon - for example locationTimer = new Timer("locationtimer", true);
  • you may need to create a new TimerTask each time you schedule (I assume timeoutReached is the TimerTask?) - for example locationTimer.schedule(new timeoutReached(), 60000);

这篇关于设置定时器超时 - 新的Timer()失败后,取消和清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆