开发者

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 T开发者_如何学运维imer 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);

        }

}


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;


Take a look at NSTimer


take a look at http://www.iphoneexamples.com/ Timer

Timers This timer will call myMethod every 1 second.

[NSTimer scheduledTimerWithTimeInterval:1 
    target:self 
    selector:@selector(myMethod:) 
    userInfo:nil 
    repeats:YES];

What if you need to pass an object to myMethod? Use the "userInfo" property. 1. First create the Timer

[NSTimer scheduledTimerWithTimeInterval:1 
    target:self 
    selector:@selector(myMethod:) //don't forget the ":"
    userInfo:myObject 
    repeats:YES];
  1. Then pass the NSTimer object to your method:

    -(void) myMethod:(NSTimer*)timer // Now I can access all the properties and methods of myObject [[timer userInfo] myObjectMethod];

To stop a timer, use "invalidate":

[myTimer invalidate];
myTimer = nil; // ensures we never invalidate an already invalid Timer
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜