January
2010

Pseudo cron jobs with WordPress

Recently I redesigned my other blog and wrote a small widget that pulls photos from my Picasa Web Albums and displays a nice little photo gallery in the sidebar. I wanted it to refresh the photos every day and thought about setting up a cron job. Unfortunately I’m on cheap web hosting where crons are not included and somehow I didn’t want to pay additional fees only because of the gallery widget.

Then I found out it’s actually possible to use pseudo cron jobs with WordPress. With version 2.1 WordPress introduced support for scheduling actions. This allows you to schedule functions that should be executed in regular intervalls.

Of course this isn’t meant to be an exact replacement for cron jobs, since it can be fairly inaccurate if your website only has a handful of visitors every day. The way it works is that you set up the scheduled action, and with every visit to your website – which means everytime WordPress is executed – it checks if a scheduled task has been due for execution since the last check, and if yes, the task will be executed. Obviously it works best if you have many visitors, but as long as you’re happy with minor inaccuracies, using the scheduling functions works just fine.

Here is a short example for how the scheduling works. It should give you the basic idea, for more information I recommend reading this very good post with more details.

// schedule daily refresh of my Picasa gallery widget
if (!wp_next_scheduled('picasa_refresh_hook')) {
	wp_schedule_event(time(), 'daily', 'picasa_refresh_hook');
}

// create a hook to the function that should be executed daily
add_action('picasa_refresh_hook', 'picasa_refresh');

// this will be run daily
function picasa_refresh() {
	...
	// download new photos
	...
}

You can put this in your functions.php but be careful with scheduling, you need to make sure that the function doesn’t get scheduled again with every visit to your website. Hence the check to see if it is already scheduled.

More information can also be found in the WordPress Documentation.