代码之家  ›  专栏  ›  技术社区  ›  s4y

NSTimer中的代码阻止自动睡眠

  •  7
  • s4y  · 技术社区  · 17 年前

    NSTimer 在我的应用程序中运行,收集一些数据并定期将其发送到服务器。在生产中,计时器将每隔几个小时启动一次。

    斯泰默 只要一分钟,它就会停止。

    一些Mac应用程序在运行时(或者如果安装了守护程序,则一直)干扰自动睡眠,这是出了名的。什么操作可以阻止系统睡眠?如何安全地运行定期任务?

    4 回复  |  直到 17 年前
        1
  •  3
  •   StKiller    14 年前

    NSLog() /var/log/system.log ,可以防止空闲睡眠。我使用一个启动的守护进程进行了测试,该守护进程将调用 NSLog(@"test") 每分钟一次,系统睡眠空闲时间为1分钟,系统从未进入睡眠状态。通过注释NSLog行,系统在1分钟后进入睡眠状态。

    这是我的建议 only reference

        2
  •  2
  •   JimDusseau    17 年前

    根据苹果的文章,访问磁盘将阻止你的计算机睡眠” 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
    

    删除setThreadPriority调用将阻止计算机睡眠。

        3
  •  1
  •   BonkaBonka    17 年前

    我有点困惑,请容忍我

    应用程序的活动将重置机器的睡眠计时器,因此,除非传输之间的延迟大于非活动时间段,否则机器将不会进入睡眠状态。我不完全确定OS X上的“活动”是什么,但如果它与Linux类似,我希望网络或磁盘IO与处于运行状态的进程一样重要——也就是说,在RAM中处理数字或搅乱数据。

        4
  •  0
  •   pgb    17 年前

    你看过launchd吗? http://developer.apple.com/MacOsX/launchd.html

    这是操作系统为自己的服务所使用的,所以我确信睡眠被考虑在内了。