What is the difference between cron and launchd? I have always used cron, but I have recently heard that launchd is better. Why? In what ways is cron better? In what ways is launchd better?
1 Answer
launchd does a lot more than cron. In addition to running programs at certain times, it can also run them based on other triggers: incoming network connection, when a file is added to a certain folder, etc. It can also relaunch a program if it crashes.
If you're interested in it specifically as a replacement for cron, the main difference is how it handles being asleep or shut down when a job is scheduled to run. In this case, cron simply doesn't run the job, but launchd will notice that a scheduled run has been missed, and run it at the next opportunity (although if it's missed multiple scheduled runs, it'll only run it once).
Also, if a job runs for so long that it's still going when its next scheduled run comes around, cron will go ahead and start a second instance of it, but launchd will skip it ('cause it's already running).
Another (related) thing that sometimes causes trouble when migrating to launchd is that it expects its jobs to stay in the foreground where it can monitor them. This causes trouble with jobs that drop themselves into the background (or "daemonize"), so you might need to tell the program not to background itself, or maybe add <key>AbandonProcessGroup</key><true/>
to the launchd plist (see this question for an example).
Edit: I should also point out some things that cron can do that launchd cannot: automatic emailing of failure reports (you'd have to write a wrapper script to do this with launchd) and user-defined jobs that run even when the user isn't logged in (a user can define launchd items in ~/Library/LaunchAgents, but they only run inside a login session).
-
-
1At least according to the Daemons and Services Programming Guide, running missed jobs later only applies to jobs scheduled during sleep (not when shut down) and by StartCalendarInterval.– LriCommented Apr 6, 2013 at 4:14