如何改变一个java计时器的时间间隔 [英] How to change a java timer's interval

查看:999
本文介绍了如何改变一个java计时器的时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个机器人的俄罗斯方块游戏。和执行时出现一个IllegalStateException

  timer.scheduleAtFixedRate(任务,0L,毫秒);

 公共无效setTimerInterval(INT毫秒){
    timer.cancel();
    定时器=新定时器();
    timer.scheduleAtFixedRate(任务,0L,毫秒);
}

我是不是错什么这样做呢?
我需要取消计时器,并创建一个新的,因为我无法改变定时器的时间间隔,除非你安排一个新的任务,对吧?

我看了一个帖子<一个href=\"http://stackoverflow.com/questions/7593134/how-to-modify-a-java-timer-interval-after-scheduling-it-for-a-fixed-rate-in-andr\">here这里是其中一个答案的话:


  

一个定时器只能使用一次调度。如果IllegalStateException异常情况并非如此,当你调用取消(),但是当您尝试重新安排计时器,重新实例只是计时器,然后安排它。否则,我不知道。


,因为它是关于暂停和恢复定时器我没有用这个问题的接受的答案。

我重新实例计时器如上图所示,但仍然有IllegalStateException异常。


解决方案

 处理程序处理程序=新的处理程序();
handler.post(新的Runnable(){    @覆盖
    公共无效的run(){
        //做任务这里
        handler.postDelayed(此,毫秒); //这里设置时间刷新的TextView
    }
});

请在毫秒全球和改变,也许这将是一个更好的解决方案。

I'm working on an android Tetris game. And an IllegalStateException occurred when executing

timer.scheduleAtFixedRate (task, 0L, milliseconds);

in

public void setTimerInterval (int milliseconds) {
    timer.cancel ();
    timer = new Timer ();
    timer.scheduleAtFixedRate (task, 0L, milliseconds);
}

Am I doing this wrongly or something? I need to cancel the timer and create a new one because I cannot change the interval of the timer unless you schedule a new task for it, right?

I read a post here and here is a quote of one of the answers:

A timer can only be scheduled once. If IllegalStateException isn't happening when you call cancel(), but when you try to reschedule the timer, just reinstantiate the timer and then schedule it. Otherwise, I'm not sure.

I didn't use the accepted answer of the that question because it's about pausing and resuming the timer.

I reinstantiated the timer as shown above but there is still a IllegalStateException.

解决方案

Handler handler = new Handler();
handler.post(new Runnable() {

    @Override
    public void run() {
        // do the task here
        handler.postDelayed(this, milliseconds); // set time here to refresh textView
    }
});

Make the milliseconds global and change that, maybe that would be a better solution.

这篇关于如何改变一个java计时器的时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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