开发者

Android how to change a TimerTask interval after shcedule?

开发者 https://www.devze.com 2023-03-31 19:56 出处:网络
timerUploadTime = new Timer(); timerUploadTimeTask = new TimerTask() { @Override public void run() { mHandler.post(new Runnable() {
timerUploadTime = new Timer();
timerUploadTimeTask = new TimerTask() {
   @Override public void run() {
      mHandler.post(new Runnable() {
        @Override
         public void run() {
             ...
       开发者_开发问答   }
      }
    });
 }
 };

timerUploadTime.schedule(timerUploadTimeTask, 1, Integer.parseInt(Utils.loadStringValue(mycontext, "refresh")));

I'd like to change my timer's interval, in an other code segment. Is there a way to do that? I dont want to retiming my code, i would like to add a new "period" interval.

How can I do that after schedule?


You can't. You'll have to cancel the current task and reschedule.


You should cancel the timer before you can set a new schedule to it.

timerTask.cancel();
timerTask = new MyTimerTask();
timer.schedule(timerTask, delay);


One way to make it happen is to schedule your Timer for running every second, and inside your timer runnable, increase a counter by one every second, then you can add if statement to check your counter mod by your desired counter variable (in terms of seconds) to return without doing anything

timerCounter++;
if((timerCounter%desiredCounter)!=0){
 return;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消