views:

117

answers:

1
+2  Q: 

Incremental Timer

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 previous 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);

}

REFACTORED CODE


@Override
public void StartScanning() {

        t.schedule(new ScanTask(),SCAN_INTERVAL_TIME);

}

class ScanTask extends TimerTask{

    @Override
    public void run() {
        wifiManager.startScan();
        scanCount++;   

        if(SCAN_INTERVAL_TIME < SCAN_MAX_INTERVAL)
        SCAN_INTERVAL_TIME = SCAN_INTERVAL_TIME + SCAN_INCREASE_INTERVAL;

        t.schedule(new ScanTask(), SCAN_INTERVAL_TIME);
    }


}

It works now but is creating a new ScanTask() every time wasteful?

+4  A: 

Here is how I would do it:

1) Schedule the task for a single execution rather than a repeated one

2) At the end of the execution (possibly in a finally block), schedule a new single execution of the task, with a longer delay. Note that you must create a new instance of the task, otherwise the timer will complain (IllegalStateException). That means that you can't use an anonymous inner class anymore.

Eyal Schneider
So I'd need to recreate scanTask every time the Timer fires?
Donal Rafferty
@Donal: According to the code above you have no heavy initialization, and no data members in the ScanTask class. Therefore the overhead of creating a new instance every 30 seconds should be minimal... The garbage collection deals with short lived objects very efficiently.
Eyal Schneider