Incremental Timer
        Posted  
        
            by Donal Rafferty
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Donal Rafferty
        
        
        
        Published on 2010-05-26T11:09:02Z
        Indexed on 
            2010/05/26
            11:11 UTC
        
        
        Read the original article
        Hit count: 462
        
I'm currently using a Timer and TimerTask to perform some work every 30 seconds.
My problem is that after each time I do this work I want to increment the interval time of the Timer.
So for example it starts off with 30 seconds between the timer firing but I want to add 10 seconds to the interval then so that the next time the Timer takes 40 seconds before it fires.
Here is my current code:
  public void StartScanning() {
    scanTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                            wifiManager.startScan();
                            scanCount++;            
                            if(SCAN_INTERVAL_TIME <= SCAN_MAX_INTERVAL){
                                SCAN_INTERVAL_TIME = SCAN_INTERVAL_TIME + SCAN_INCREASE_INTERVAL;
                                t.schedule(scanTask, 0, SCAN_INTERVAL_TIME);
                            }
                        }
               });
        }};
        Log.d("SCAN_INTERVAL_TIME ** ", "SCAN_INTERVAL_TIME ** = " + SCAN_INTERVAL_TIME);
        t.schedule(scanTask, 0, SCAN_INTERVAL_TIME);
}
But the above gives the following error:
05-26 11:48:02.472: ERROR/AndroidRuntime(4210): java.lang.IllegalStateException: TimerTask is scheduled already
Calling cancel or purge doesn't help.
So I was wondering if anyone can help me find a solution?
Is a timer even the right way to approach this?
© Stack Overflow or respective owner