How to modify a java timer interval after scheduling it for a fixed rate in android? [duplicate]

随声附和 提交于 2019-12-12 18:23:09

问题


I have a service which has one Timer. I call timer.scheduleAtFixedRate() in the onStart() callback method. But I have to alter the timer interval depending on the value of a variable. I found no function for timer to alter its interval. So I thought to cancel the timer and re-schedule when that condition is met. But I am checking the condition with in the timerTask itself. So when I tried to cancel the timer in the TimerTask, it throws IllegalStateException. Can anybody give me some solution?


回答1:


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.




回答2:


Netiher Timer.cancel() nor TimerTask.cancel() throws IllegalStateException. That is thrown when you try to schedule a task on a cancelled Timer.

Solution: don't cancel the Timer; cancel the TimerTask.



来源:https://stackoverflow.com/questions/7593134/how-to-modify-a-java-timer-interval-after-scheduling-it-for-a-fixed-rate-in-andr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!