How do you run a PHP script every 1 minute using a plist file with launchd (launchctl) in MacOS?

277 views Asked by At

So how do you run a PHP script once every 1 minute using a plist file with launchd (launchctl) in MacOS? This was a question I had that took forever to find the answer to, but I did eventually! I'm using my answer to make jobs on a Mac instead of cron or crontab, which is what you would normally use in Linux/Unix. Checkout my answer below!

1

There are 1 answers

0
Juno Sprite On

Answer

Create a new plist file ~/Library/LaunchAgents/com.yourusername.yourscripttype.plist and add the follow code to it, changing everything that should be changed:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>com.yourusername.yourscripttype</string>
    <key>ProgramArguments</key>
    <array>
      <string>/absolute/path/to/php</string>
      <string>/absolute/path/to/app/subfolders/script.php</string>
    </array>
    <!-- <key>StandardOutPath</key>
    <string>/tmp/MoodleError.out</string>
    <key>StandardErrorPath</key>
    <string>/tmp/MoodleError.err</string> -->
    <key>WorkingDirectory</key>
    <string>/absolute/path/to/app/</string>
    <key>StartInterval</key>
      <integer>60</integer>
    <key>RunAtLoad</key>
    <true/>
  </dict>
</plist>

Set permissions for this plist file:

chmod 644 ~/Library/LaunchAgents/com.yourusername.yourscripttype.plist

Confirm permission for your new file matches the existing plist files:

ls -l ~/Library/LaunchAgents/

Load the new file:

launchctl load com.yourusername.yourscripttype.plist

You should be good to go.

Notes

  • com.whatevername.whateverscript.plist is convention in MacOS, so use it.
  • Manually test your PHP script with launchctl start ~/Library/LaunchAgents/com.yourusername.yourscripttype.plist
  • WARNING: Uncomment the StandardOutPath and/or StandardErrorPath lines in the above file if you want to see script output or errors to confirm your script is running properly, but DON'T LEAVE THEM IN OR ELSE YOU'LL BE ADDING TO THE LOG FILES EVERY MINUTE WHICH WILL QUICKLY DESTROY YOUR SYSTEM'S MEMORY!
    <!-- <key>StandardOutPath</key>
    <string>/tmp/MoodleError.out</string>
    <key>StandardErrorPath</key>
    <string>/tmp/MoodleError.err</string> -->