Creating an autonomous service for your WordPress plugin using wp-cron

When integrating third party API’s with a WordPress plugin, a lot of developers take the easy route by forcing all of the interactions to occur on submit; the end user pays the price by waiting through an extended submit process that has them staring at an hourglass or loading screen for far longer than they should. If the end user is done when the submit button is hit, don’t make them wait through your post process just to get to a thank you screen. Store the data locally, and use an autonomous service to figure out what to do with it asynchronously.

WordPress makes this easy with the wp-cron function. You can implement a schedule, and call your service according to that schedule. Let’s begin.

Set your local timezone, and add your new service schedule to the chron:

// Build our scheduling functions
date_default_timezone_set('America/New_York');

add_filter( 'cron_schedules', 'ezdaemon_schedule');
function ezdaemon_schedule(){
	return array(
		'in_per_two' => array(
			'interval' => 60 * 2,
			'display' => 'Every two minutes'
		)
	);
}

 

Call the function you want run according to the new schedule you’ve just created:

// Now schedule our event
if( !wp_next_scheduled( 'ezDaemonService' )){
	wp_schedule_event( time(), 'in_per_two', 'ezDaemonService' );
}

add_action( 'ezDaemonService', 'ezDaemonProcess' );

 

We want to make sure that our service doesn’t hang around if the plugin has been deactivated, so clear it with the deactivation hook:

// Deactivate our schedule when the plugin is turned off
register_deactivation_hook( __FILE__, 'clear_ezdaemonschedule' );
function clear_ezdaemonschedule(){
  wp_clear_scheduled_hook( 'ezDaemonService' );
}

 

…and finally, tell the service what to do:

function ezDaemonProcess(){
// Do stuff here every time our schedule fires off
echo 'foo';
}

 

Et voila! Now your function isn’t reliant on your end users waiting for completion. You get a rapid form submit, they go off about their business, and your software works behind the scenes doing what it’s supposed to do without needing to be supervised.

There’s one caveat: wp-cron is refreshed each time a page is loaded on the site (front end or back end), and if your site has little to no traffic, the scheduler may run behind.

What cool things have you done with wp-cron? Let me know in the comments.