我在我的应用程序中运行了一个NSTimer,它收集一些数据并定期发送到服务器.在生产中,计时器将每隔几个小时发射一次.
我担心干扰自动睡眠.在测试中,计时器和睡眠时间的某些组合完全阻止自动睡眠 – 显示器休眠,系统保持运行.将我的NSTimer设置为一分钟始终会停止它.
一些Mac应用程序因运行时干扰自动睡眠而臭名昭着(或者如果他们安装了一个守护进程,则一直都是这样).什么操作会阻止系统进入睡眠状态?如何安全地运行定期任务?
解决方法
根据Apple的文章“
Mac OS X: Why your Mac might not sleep or stay in sleep mode”,访问磁盘将使您的计算机无法入睡.
此外,我的测试表明,线程的优先级也会影响计算机是否会睡眠.以下带有计时器的代码将允许计算机进入睡眠状态.
- @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