Android timer question

Hello, I am creating an application that will execute a block of code at certain periods of time (for example, every 30 minutes). I would like this period to be strict, I mean that I would like to be sure that the period will be 30 minutes, not 28 minutes or whenever os wants to execute it.

I have a Timer object and use it like this:

timer=new Timer(); timer.scheduleAtFixedRate(new GetLastLocation(), 0, this.getInterval()); where GetLastLocation is a handler class that extends TimerTask. This works great, but I would like to change the interval, what I am doing now, using timer.scheduleAtFixedRate twice and changing the interval parameter to say newInterval, but I think it’s just having two timers running each interval and a new interval now, I right?

I also try to cancel the timer and then use the scheduleAtFixedRate () method, but this throws an exception, as indicated in the documentation.

what can i do to fix this? welcomes maxsap

+3
source share
3 answers

You cannot schedule a timer that has already been canceled or scheduled. You need to create a new timer for it.

Timer timer;
synchronized void setupTimer(long duration){
  if(timer != null) {
    timer.cancel();
    timer = null;
  }
  timer = new Timer();
  timer.scheduleAtFixedRate(new GetLastLocation(), 0, duration);
}
setupTimer , . PS: , . - (, ), , "". , ( , , Object.wait(long), ).
+5

TimerTask ( ) .

public final void checkFunction(){ 
  t = new Timer();
  tt = new TimerTask() {
      @Override
      public void run() {
           //Execute code...
      }
  };
  t.schedule(tt, 10*1000); /* Run tt (your defined TimerTask) 
  again after 10 seconds. Change to your requested time. */
}

, , onCreate onResume/onStart.

+1

You can also use a handler instead of a timertask.

Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
        if(what.msg==1)
        {
            what.msg==2;
        }       
    }   
};
mHandler.sendEmptyMessageDelayed(1, 10* 1000);//10*1000 10 sec.specify your time 
0
source

Source: https://habr.com/ru/post/1768208/


All Articles