NSTimer,NSRunloop和深度睡眠mac

时间:2013-04-05 19:55:11

标签: objective-c macos nstimer sleep nsrunloop

我正在使用mac上的objective-c编写应用程序,我需要一些帮助。每天23:59,我的应用程序正在调用一种方法来生成

报告
NSTimer *timer = [[NSTimer alloc]
                  initWithFireDate:endOfTheDay
                  interval:0.0
                  target:self
                  selector:@selector(endDay)
                  userInfo:nil
                  repeats:NO];

[[NSRunLoop currentRunLoop] addTimer:timer forMode: NSDefaultRunLoopMode];
除非计算机处于深度睡眠模式,否则

正在按预期工作。问题是:我需要计时器在一天中的这个确切时刻调用方法,即使它处于睡眠模式。我不想阻止睡眠。你能救我吗?

提前致谢!

2 个答案:

答案 0 :(得分:3)

查看IOPMSchedulePowerEvent:

 IOReturn IOPMSchedulePowerEvent(
   CFDateRef time_to_wake,
   CFStringRef my_id,
   CFStringRef type);

请注意,必须从root调用此方法。

答案 1 :(得分:0)

我实际上做了什么,是用我的参数创建一个pmset事件,然后用一个像这样的AppleScript行以root身份运行它:

NSDate *currentDate = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *currentComponents = [cal components: NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:currentDate];
NSDate *lastDay = [cal dateFromComponents:currentComponents];
NSDateComponents *aDay = [[NSDateComponents alloc] init];
aDay.day = 1;
NSDate *tonight = [cal dateByAddingComponents:aDay toDate:lastMidnight options:0];

NSString *command = [NSString stringWithFormat: @"pmset schedule wake %@, tonight]
NSString *scriptLine= @"[NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges, command]"

NSAppleScript *myScript = [[NSAppleScript new] initWithSource:scriptLine];
NSAppleEventDescriptor *res = [myScript executeAndReturnError:&errorInfo];

基于 AuthorizationExecuteWithPrivileges is deprecated