可可 – NSTimer中的代码可防止自动睡眠

前端之家收集整理的这篇文章主要介绍了可可 – NSTimer中的代码可防止自动睡眠前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中运行了一个NSTimer,它收集一些数据并定期发送到服务器.在生产中,计时器将每隔几个小时发射一次.

我担心干扰自动睡眠.在测试中,计时器和睡眠时间的某些组合完全阻止自动睡眠 – 显示器休眠,系统保持运行.将我的NSTimer设置为一分钟始终会停止它.

一些Mac应用程序因运行时干扰自动睡眠而臭名昭着(或者如果他们安装了一个守护进程,则一直都是这样).什么操作会阻止系统进入睡眠状态?如何安全地运行定期任务?

解决方法

根据Apple的文章Mac OS X: Why your Mac might not sleep or stay in sleep mode”,访问磁盘将使您的计算机无法入睡.

此外,我的测试表明,线程的优先级也会影响计算机是否会睡眠.以下带有计时器的代码将允许计算机进入睡眠状态.

  1. @implementation AppController
  2.  
  3. -(void)timerFired:(NSTimer *)aTimer
  4. {
  5.  
  6. }
  7.  
  8. -(void)spawnThread
  9. {
  10. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  11. [NSThread setThreadPriority:0.0];
  12.  
  13. [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
  14.  
  15. while(1) //Run forever!
  16. {
  17. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:300]];
  18. }
  19.  
  20. [pool drain];
  21. }
  22.  
  23. -(void)awakeFromNib
  24. {
  25. [NSThread detachNewThreadSelector:@selector(spawnThread) toTarget:self withObject:nil];
  26. }
  27.  
  28. @end

删除setThreadPriority调用将阻止计算机休眠.

猜你在找的iOS相关文章