我NSTimer在我的应用程序中运行,它收集一些数据并定期发送到服务器.在生产中,计时器将每隔几个小时启动一次.
我担心干扰自动睡眠.在测试中,计时器和睡眠时间的某些组合完全阻止自动睡眠 - 显示器休眠,系统继续运行.将我设置NSTimer为一分钟总是会停止它.
一些Mac应用程序因运行时干扰自动睡眠而臭名昭着(或者如果它们安装了一个守护进程,则一直都是如此).什么操作会阻止系统进入睡眠状态?如何安全地运行定期任务?
根据苹果公司的文章“ Mac OS X:为什么你的 Mac 可能无法睡眠或保持睡眠模式”,访问磁盘将阻止你的计算机进入睡眠状态。
此外,我的测试表明,线程的优先级也会影响计算机是否睡眠。以下带有计时器的代码将允许计算机进入睡眠状态。
@implementation AppController
-(void)timerFired:(NSTimer *)aTimer
{
}
-(void)spawnThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread setThreadPriority:0.0];
[NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
while(1) //Run forever!
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:300]];
}
[pool drain];
}
-(void)awakeFromNib
{
[NSThread detachNewThreadSelector:@selector(spawnThread) toTarget:self withObject:nil];
}
@end
Run Code Online (Sandbox Code Playgroud)
删除 setThreadPriority 调用将阻止计算机休眠。