【问题标题】:NSTimer, NSRunloop and deep sleeping macNSTimer、NSRunloop 和深度睡眠 mac
【发布时间】:2013-03-28 08:52:50
【问题描述】:

我正在 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];

除非计算机处于深度睡眠模式,否则它会按预期工作。问题是:即使它处于睡眠模式,我也需要计时器在一天中的这个确切时刻调用该方法。我不想阻止睡眠。你能帮帮我吗?

提前致谢!

【问题讨论】:

    标签: objective-c macos nstimer sleep nsrunloop


    【解决方案1】:

    我实际上做的是使用我的参数创建一个 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

    【讨论】:

      【解决方案2】:

      查看 IOPMSchedulePowerEvent:

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

      请注意,这必须从根目录调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-07
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        • 2023-03-22
        • 2012-12-02
        相关资源
        最近更新 更多