Search code examples
iphoneobjective-cios4timertask

iPhone equivalent of Timer and TimerTask for periodic tasks


I'm trying to port an Android app to an iPhone. On Android I could easily process data every 60 seconds by using a Timer class with TimerTasks using scheduleAtFixedRate: timer.scheduleAtFixedRate(task,15000, epochLengthMs);

Thank you!

Is there something similar I can use on iPhone?

protected void startTimer(){

    if(timerStarted){
        //avoid duplicate timers! 
    }else{

        running = true;
        timerStarted = true;

        if(D)Log.w(TAG,"*Timer Started*");
        timer = new Timer();
        readyToProcess = true;
        EpochCounterTask task = new EpochCounterTask();
        AutoSaveTask saveTask = new AutoSaveTask();

        //give statMagnitude enough time to get values
        //after 15 sec, every 60 sec
        timer.scheduleAtFixedRate(task,15000, epochLengthMs);
        timer.scheduleAtFixedRate(saveTask,645000, 600000);

        }

}

Solution

  • You will need to create two NSTimers - one for the epoch counter and one for the autosave task. Something like this:

    - (void)startTimer {
    
    if(timerStarted){
        //avoid duplicate timers! 
    }else{
    
        running = true;
        timerStarted = true;
    
        readyToProcess = true;
    
        epochTimer = [[NSTimer scheduledTimerWithTimeInterval:epochSeconds 
                                            target:self
                                            selector:@selector(processEpochTimer:)
                                            userInfo:nil
                                            repeats:YES] retain];
    
        autosaveTimer = [[NSTimer scheduledTimerWithTimeInterval:autosaveSeconds 
                                            target:self
                                            selector:@selector(processAutosaveTimer:)
                                            userInfo:nil
                                            repeats:YES] retain];
        }
    }
    

    You also need to define the following handler methods, which are called when the timers fire:

    - (void)processEpochTimer:(NSTimer*)theTimer;
    - (void)processAutosaveTimer:(NSTimer*)theTimer;