首页 > 解决方案 > 如何在计算机睡着或用户注销时触发 NSTimer

问题描述

我想在 6 小时后触发计时器。但由于我的电脑处于睡眠模式,定时器在 6 小时后没有触发。我在 6 个多小时后登录计算机后 2 分钟触发它。即使用户处于注销或系统睡眠模式,是否可以触发计时器?

标签: objective-cmacoscocoanstimer

解决方案


This is a simple way of doing it. Create an NSDate for the upcoming event and set up a timer for comparing current time to that timestamp. This example runs once every second.

- (void) waitFor:(CGFloat)seconds {
    // Set the time to wait
    NSTimeInterval timeInSeconds = seconds; 
    __block NSDate *wait = [[NSDate date] dateByAddingTimeInterval:timeInSeconds];

    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSDate *time = [NSDate date];
        if ([time timeIntervalSinceDate:wait] > 0) {
            // Do something
        }
    }];
}

This way, the process will run immediately after waking up your computer.

EDIT: Older threads (such as NSTimer continue during sleep mode) suggest that you would need to reschedule the NSTimer after wake, but it doesn't seem to be the case anymore.


推荐阅读