'Prevent NSTimer from firing when in sleep / PowerNap

How can I prevent a (slightly non-standard) NSTimer from firing on macOS, when the MacBook's lid is closed and the machines is supposed to be at sleep? Or more specifically, how can I opt-out of Power Nap.

Here is the code I use to setup the timer:

 self.timer = [NSTimer scheduledTimerWithTimeInterval:60 * 5
                                              target:self
                                            selector:@selector(scheduleTimerFired:)
                                            userInfo:nil
                                             repeats:YES];

for (NSString *mode in @[NSModalPanelRunLoopMode, NSDefaultRunLoopMode, NSRunLoopCommonModes]) {
    [[NSRunLoop currentRunLoop] addTimer:self.timer
                                 forMode:mode];
};

Firing during sleep causes issues, as this timer starts communication with a remote server using OAuth tokens. These tokens might be refreshed in the process. Since the Mac is at sleep, the users's keychain seems to be locked, which prevents refreshed tokens from being written to it (error: user interaction not allowed).

Therefore, I'd rather not have the timer executed at all when in sleep mode.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source