Work with CRON in CMS WordPress

Work with CRON in CMS WordPress

In this short note, I’ll show a simple example of working with cron in a popular engine like WordPress.

For a regularly recurring task (i.e., code that should run on a regular basis), you can use the following code snippet:

add_filter('cron_schedules', function ( $schedules ) {
	$schedules['10sec'] = array(
		'interval' => 10,
		'display'  => __('Every 10 sec'),
	);
	return $schedules;
});

add_action('init', function(){
	if(!wp_next_scheduled('post_event_cron_action'))
	{
		wp_schedule_event( time(), '10sec', 'post_event_cron_action');
	}
});

add_action('post_event_cron_action', function () {
	echo 'Mail sent';
	mail('test@example.com', 'Test subject', 'Test body');
});

What are we doing here? First, we define a custom interval for running the code — that is, the time after which our code will be executed:

add_filter('cron_schedules', function ( $schedules ) {
	$schedules['10sec'] = array(
		'interval' => 10,
		'display'  => __('Every 10 sec'),
	);
	return $schedules;
});

We use the "cron_schedules" filter with an anonymous function. In the single $schedules parameter, we add a custom interval (as a new array key), assigning it a name and specifying the number of seconds for the interval to repeat.

Second:

add_action('init', function(){
	if(!wp_next_scheduled('post_event_cron_action'))
	{
		wp_schedule_event( time(), '10sec', 'post_event_cron_action');
	}
});

We “schedule” our cron task, checking first if it already exists (has been scheduled previously). The third parameter "post_event_cron_action" is the hook name for our cron task. The second parameter is the interval name (as defined earlier), and the first is the initial timestamp from which the hook should start running.

Third (and final):

add_action('post_event_cron_action', function () {
	echo 'Mail sent';
	mail('test@example.com', 'Test subject', 'Test body');
});

This is the actual hook and the code it will execute.

One BUT!
Not sure how it works for others, but personally, the cron didn’t trigger just by refreshing a normal page. However, it did work when accessing wp-cron.php directly via the site’s URL. Maybe this behavior only happens on localhost. Although some say it should work with a regular page refresh. Time will tell.

What are your thoughts on this? Thanks!

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *