Cron jobs--or more accurately “Crontab”--is a common Linux application you’ll hear about early on in your ventures into web development. Cron jobs let you trigger code in intervals in the background on your server. Many crumby hosting providers provide a way to trigger “cron jobs” in entered intervals.
If you’re running your own server, you’ll type a command such as:
# crontab -e
and see a simple text file that line by line lists scripts to trigger in given intervals. For example, one might like this:
1 11 * * * commandname >> /var/log/log-name.log
That one for example will trigger the command, “commandname” every day at 11am and record any output produced by that command into the file log-name.log.
The idea behind cron is simply that you can trigger routine tasks in recurring intervals. Other examples of such intervals are every minute, every 30 minutes, once a week, once a month, etc.
You can even trigger PHP scripts. Yii has tools to create “console applications,” i.e. applications/commands you can trigger from the command line of your server. To learn more about them, check out the tutorial on the Yii site:
Overall, the thing to note is that cron is extremely easy to use. It’s not anything crazy. Write a PHP script using the Yii console application tools, and trigger it with a simple line in the crontab file. That’s it. The next thing to note is that cron isn’t the solution for everything. Often Daemons may be the real answer, and we’ll cover that in the next article. The general idea is that cron scripts can often overlap and get clogged, whereas daemons are constantly running in realtime and you can write logic that solves how to deal with these jams.
I’ll end this tutorial with an example of what cronjobs are good for so you know what challenges to look out for that are nicely served with an entry in your crontab file as a solution. Imagine you want to generate a report each day, maybe with the # of new user signups and other such data. Well, cron is perfect. Trigger your PHP script that will check the database for the # of new users since the same time the day before and email the result to yourself. Or perhaps, you are seeding your site with content from RSS feeds. You can write a PHP script to check these RSS feeds daily (or hourly or whatever) daily and insert the new articles in your own database of articles.