Simple Cron
One of the questions that I seem to get asked most about building a browsergame is “how do I make things happen periodically?”.
The answer is actually very simple, and lies with a utility that comes on all Linux servers called cron.
Cron exists to run periodic, scheduled tasks for you – based on a file called a “crontab”. You can run any command you want at any time that you want using cron.
In order to edit your crontab, get access to the console of your webserver and type the following command:
crontab -e
If your server doesn’t have any cronjobs currently in place, you’ll just see an empty file. We will be editing this file to make things happen periodically.
The first five columns in your crontab correspond to measurements of time; the sixth column is the command to run. The time columns are for the hour, minute, day of the month, month, and day of week to run the command on. Here’s what a command that runs every day at 3:30 AM might look like:
30 3 * * * echo "ran cron at 3:30 AM" > /var/log/misc/crons.log
If you wanted to make something happen periodically in your game, you would just need to write the code for whatever you wanted to have happen periodically, and then write a cronjob to call it with the proper parameters.
You can also configure cronjobs to run in shorter intervals, or even at multiple intervals:
0 */3 * * * echo "this cronjob runs every 3 hours"
The above cronjob will run every 3 hours – and the one below will run only once a month:
0 0 1 * * echo "this cronjob runs every 3 hours"
If you don’t have access to your server’s command line to play around with cron, try talking to your webhost or investigating your control panel if you have one – in most cases, webhosts that won’t allow you command-line access will still allow you to create your own crontabs.
Luke is the primary editor of Building Browsergames, and has written a large portion of the articles that you read here. He generally has no idea what to say when asked to write about himself in the third person.
-
bardic




