我正在开发一个应用程序,需要在特定时间(准确地说是整点过 15 分钟)调用一个方法。有没有办法在不消耗大量 CPU 和电池生命周期的情况下实现这一点?我尝试过搜索,但在任何地方都找不到答案。
最佳答案
他们让这变得非常简单。分配一个 NSTimer
并使用触发日期对其进行初始化,使用:
-(id)initWithFireDate:(NSDate *)date
interval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats
然后使用以下命令将其添加到运行循环中:
-(void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode
在运行循环上,例如[NSRunLoop currentRunLoop]
。不知道这是否会唤醒设备,或阻止其休眠。
编辑一些示例代码
// 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];
和
-(void)stuff:(NSTimer*)theTimer
{
if ( done ) [theTimer invalidate];
}
关于iphone - 当 iPhone 应用程序到达一天中的特定时间时,我如何收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3320859/