2

I have a crontab job scheduled to run every hour. I like to sleep and I also enjoy giving my macbook the same privileges. Unfortunately, cron does not execute when the system is asleep. Is there a way to do the following:

Every hour,

  1. Check if computer is already asleep.
  2. If asleep, wake up computer.
  3. Wait for crontab job to finish.
  4. Go back to sleep if computer was previously asleep.

I understand I can use pmset to schedule wake/sleep for every hour, but I want to selectively put the computer back to sleep (conditional on whether or not it was asleep before the wake routine started running).

1 Answer 1

1

launchd runs jobs that were scheduled during sleep (by StartCalendarInterval) after waking up. You could go back to sleep if the script is run at a delayed time.

for h in {0..23}; do sudo pmset repeat wake MTWTFSS $h:00:00; done

~/Library/LaunchAgents/test.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>test</string>
    <key>Program</key>
    <string>/Users/username/Desktop/test</string>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Minute</key>
        <integer>59</integer>
    </dict>
</dict>
</plist>

~/Desktop/test:

#!/bin/bash

say a
[[ $(date +%-M) -lt 10 ]] && osascript -e 'tell app "System Events" to sleep'

chmod +x ~/Desktop/test, and run launchctl load ~/Library/LaunchAgents/test.plist or log out and back in. You have to unload and load the plist to apply changes. See man launchd.plist for more information.

If you wake the computer up manually at 7:59:55, it might go back to sleep though.

1
  • Unless I'm misunderstanding something, it seems that the pmset command given won't actually wake the machine hourly: pmset -g sched shows that only one repeating event gets scheduled (each iteration of the loop replaces the last). pmset relative wake 3600 may be a viable alternative to actually waking hourly (though I haven't yet tried this myself).
    – mrkj
    Nov 29, 2015 at 18:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .