Automate Jobs on a Mac
While completing the data science project, I found I need to automate some job to help me crawl data from some API which should be invocated in a period style. So I investigated automation on a Mac.
The tool we need for this is the launchctl command. And the files we will be playing with is the plist files under ~/Library/LaunchAgents, which belongs to only the user but not the system (so it’s run by the user). Each file under this folder is a describing doc for a job. We can specify the BASH script it runs and when to run.
It’s an XML file, so everything should be in the tags. When you forget what to write in a XML file, you can simply copy and paste another file in the same folder, and this is how I did it. Within the top level dict tag, the fileds are ordered by pairs of key/value. Let’s just focus on the fileds we care:
- Label: this is the filename of the current file. It’s suggested to be named in com.SOMEPACKAGE.plist
- ProgramArguments: that’s the command been invocated when job is up
- StartCalendarInterval: the time when the command is run
- StandardOutPath/StandardErrorPath: the two files to accept error and std out.
The simplies plist should have these five fields. Take care that the program arguments is an array, the each parameter exists in a single tag named string
Commands:
launchctl load somejob.plist # load the job
launchctl list # list all jobs
launchctl stop somejob.plist # stop the job
launchctl unload somejob.plist # remove the job
launchctl start somejob.plist # test run the job once
Things to remember:
- the command should be runnable, e.g. a script needs to have execute premission.
- load before start
- jobs under this folder will be load by the system everytime system is started. So remember to remove the file if you don’t need it anymore.