objective-c - 如何在计算机睡着或用户注销时触发 NSTimer
问题描述
我想在 6 小时后触发计时器。但由于我的电脑处于睡眠模式,定时器在 6 小时后没有触发。我在 6 个多小时后登录计算机后 2 分钟触发它。即使用户处于注销或系统睡眠模式,是否可以触发计时器?
解决方案
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.
推荐阅读
- python - 如何在日期时间库python中获取当前时间的时间对象
- flutter - 即使在 Flutter 中使用 setState 后,图像也没有更新
- excel - 使用 VLOOKUP 不仅匹配第一个值
- ios - RxSwift - 启动和更新倒数计时器
- stata - 对具有相同 ID 的每个观察进行约束
- html - 在 HTML 文件中使用 SVG 的正确方法
- mysql - 在 mysql 工作台的列中确定事件之间的平均差异(以天为单位)
- prolog - PROLOG:如何在 prolog 中创建 KMP 算法?
- sql-server - 执行存储在 SQL Server 表中的语句
- javascript - jsPDF问题:未捕获(在Promise中)错误:无法加载dompurify:错误:找不到模块'dompurify'