Schedule a script to run automatically even if Mac is sleeping

launchdmacpythonsleepterminal

I'm really struggling with this.

Basically I want to run a Python script every 3 hours on my Mac. Even if I'm not using the Mac.
So even if the Mac is asleep I want it to wake up and run the script.

My method of attack is as follows:

  1. I've downloaded a third party app called “scenario” that will run scripts when the Mac wakes up.

  2. I have put an Apple script in scenario that will call the Python file.

  3. The Python file runs the couple of commands I need it to run and then sets a pmset wake up call scheduled for 3 hours after the current time.

Now the whole thing is clunky and patched together. To be honest it doesn't really work well because when I wake the laptop myself the code is executed, hence messing up the schedule.

There has to be a better way. Does anyone know where I can look / who could help me on this one?

I have looked launchd but I don’t think that will run commands when the laptop is asleep.

My current way makes the laptop wake up and execute code on wake up but how can I counter my problem above?

Best Answer

I think the idea of using pmset to schedule a wake-up is a good idea. I think there are some other tools (Caffeine?) that help with wake-up or sleep schedules, but I'd stic with pmset.

Just put a condition in the AppleScript or Python script to check the last time the script was run (based on a log entry, or a "touched" file), and if it's less than 3 hours since the last run, exit the script.

If you wake the Mac before the 3 hours, you'll need a way to reset the next script-run time. But, you kind of have to solve that problem already for times when you're using the Mac for more than 3 hours straight.

So, I'd combine Scenario with cron running the same script, maybe once a minute. Same rules: script checks the last run time, exits if it's too early to run. So now there are 2 ways to trigger your script:

  1. Mac has been asleep for 3 hours, pmset wakes it up
  2. Mac has been asleep, you wake it before 3 hours
  3. Mac is awake, it's been a minute since the last check

In scenario 1, your script runs fully. in #2, it checks and exits. In #3, it checks and might exit (too early) or might run fully.

Related Question