views:

75

answers:

2

I am working on an application that needs a method to be called at a certain time (15 minutes past the hour to be exact). Is there a way to make this happen without consuming a ton of CPU and battery life? I've tried searching and just can't find an answer anywhere. Any help is appreciated. Thanks!

+3  A: 

They made this really easy. Alloc an NSTimer and initialize it with the fire date, using:

-(id)initWithFireDate:(NSDate *)date
      interval:(NSTimeInterval)seconds
      target:(id)target
      selector:(SEL)aSelector
      userInfo:(id)userInfo
      repeats:(BOOL)repeats

then add it to the run loop using:

-(void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode

on the run loop, e.g. [NSRunLoop currentRunLoop]. Don't know if this will wake the device, or prevent it from sleeping.

edit some example code

// start in 5 minutes
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:300];

// fire every minute from then on
NSTimer *t = [[NSTimer alloc]
    initWithFireDate:date
    interval:60
    target:self
    selector:@selector(stuff:) // -(void)stuff:(NSTimer*)theTimer
    userInfo:nil
    repeats:YES
];

// make it work
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];

and

-(void)stuff:(NSTimer*)theTimer
{
    if ( done ) [theTimer invalidate];
}
mvds
+1 nice and simple.
Dave DeLong
+2  A: 

If you need this to happen while your application is not running, have a look a UILocalNotification in iOS 4.0. It's unclear whether your application is running at the time that you need this notification or not, but in either case this class should get you pointed in the right direction.

http://developer.apple.com/iphone/library/documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#//apple_ref/occ/cl/UILocalNotification

Wireless Designs