Cronjob in WordPress

WordPress provides a great tool imitating unix cronjob. You can schedule your tasks easily.
Sometimes there’s a necessity to use a scheduled task e.g. cashing, sending emails, creating reports.


While creating your plugin, first create your schedule periods.

function create_my_schedules($schedules)
	if (!isset($schedules["5min"])) {
		$schedules["5min"] = array(
			'interval' => 5 * 60,
			'display' => __('Once every 5 minutes'));
	if (!isset($schedules["3min"])) {
		$schedules["3min"] = array(
			'interval' => 2 * 60,
			'display' => __('Once every 3 minutes'));
	return $schedules;

add_filter('cron_schedules', 'create_my_schedules');

Next we create an event, which will run our task function.

add_action('publish_my_posts_event', 'publish_my_posts');

function schedule_my_cron()
	wp_schedule_event(time(), '5min', 'publish_my_posts_event');

if (!wp_get_schedule('publish_my_posts_event')) {
	add_action('init', 'schedule_my_cron', 10);

The last condition allowes to avoid scheduling already scheduled event. OK! There’s only one thing left to do. To create our task function.

function publish_my_posts()
	// here put your task logic

That’s it.