maxsap
maxsap

Reputation: 3001

android timer question

Hello I am building an application that is going to execute a block of code at fixed periods of time (e.g. every 30 minutes). I would like that period to be strict,what I mean is that I would like to be guaranteed that the period will be 30 minutes and not 28 minutes or whenever the os whants to execute it.

I have a Timer object and use it as follows:

timer=new Timer(); timer.scheduleAtFixedRate(new GetLastLocation(), 0, this.getInterval()); where GetLastLocation is the handler class wich extends TimerTask. This works fine,but I would like to be able to change the interval,what I am currently doing is using timer.scheduleAtFixedRate twice and changing the interval parameter to lets say a newInterval but I think that this is just having two timers execute every interval and new Interval now, am I correct?

also I have tries cancelling the timer and then using the the method scheduleAtFixedRate() but this throws an exception as stated in the documentation.

what can I do to fix this? regards maxsap

Upvotes: 3

Views: 2078

Answers (3)

Sharad Mhaske
Sharad Mhaske

Reputation: 1103

You can also use handler instead of 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 

Upvotes: 0

Wroclai
Wroclai

Reputation: 26925

Define your task inside a TimerTask (as you did) and schedule the timer.

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. */
}

Just execute the function wherever you want, for example in onCreate or in onResume/onStart.

Upvotes: 1

bhups
bhups

Reputation: 14895

you can not schedule on a timer which was already cancelled or scheduled. You need to create a new timer for that.

Timer timer;
synchronized void setupTimer(long duration){
  if(timer != null) {
    timer.cancel();
    timer = null;
  }
  timer = new Timer();
  timer.scheduleAtFixedRate(new GetLastLocation(), 0, duration);
}
Now you can call setupTimer whenever you want to change the duration of the timer.
PS: In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Upvotes: 5

Related Questions