How to schedule a script which executes daily? [OSX]

2k views Asked by At

I have a python script which I want to run daily at let's say 9 am. But if the system is not on at that time, the script should run as soon as the computer gets turned on again.

I'm looking for something like anacron.

How can I achieve this? Cron job doesn't fulfill my purpose.

2

There are 2 answers

0
Gordon Davisson On

Create a Launch Daemon file, set its ownership to root:wheel and permissions to 644, and place it in /Library/LaunchDaemons. At minimum, the file should contain something like this:

<?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>local.maintenance</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/your/script</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>9</integer>
        <key>Minute</key>
        <integer>0</integer>
    </dict>
</dict>
</plist>

Note that although a missed run of the daemon will be made up at the next opportunity, it'll "coalesce" multiple missed runs. For example, if the computer is off for 5 days, the daemon will be run just once when it finally starts up.

1
wij On

Gordon's answer is right; launchd will get the job done.

A few tips that may help:

  • Be aware of the difference between Launch Daemons (they run at boot) and Launch Agents (they run on login). Basically, do you want your script to run only if you are already logged in? This post is helpful: http://www.grivet-tools.com/blog/2014/launchdaemons-vs-launchagents/
  • Use LaunchControl http://www.soma-zone.com/LaunchControl/. It's a GUI that helps you manage your jobs and simplifies dealing with plists. With it, just create a new User Agent (or Global Daemon), specify the time of day with "StartCalendarInterval" and it will work. If it doesn't, LaunchControl will help you debug too (by helping you pipe to standard error and standard out).