Tutorials UPDATED: 18 February 2022

How WordPress Cron Works

Tassos Antoniou

8 min read
Image for How WordPress Cron Works

Have you ever wondered what WP-Cron is? If so, then this is the perfect article for you to learn all you need to know about WordPress scheduled tasks.

Cron (Command Run On) is a utility started in UNIX systems, and later evolved on the LINUX distributions that was proposed as a time-based job scheduler. 

A cron job is a task that is performed repetitively or as a one-time task. Over the years it has mostly been used as a system administration tool for running tasks automatically.

WordPress Cron

While running a WordPress website, some tasks are performed in the background that need to be executed periodically, like checking for updates of themes and plugins, scheduled posts, transients to be deleted and many more. These time-based scheduled tasks are handled by the WP-Cron.

In your WordPress installation, the file related to cron jobs is the wp-cron.php file, located in the root folder of your installation.

The wp-cron.php file contains the code for the automated tasks related to updates and posts. 

How it Works

The WP-Cron checks the tasks list on every page load and executes accordingly.  

If the moment the page is loaded, a task is due, it is added in a queue. That way WordPress ensures that even the due events will be fired and not be skipped and eventually all the tasks will be executed on that page load. 

It is natural if this seems irrational to you, but think about the alternative. In a shared hosting environment, as it is in majority, you should have access to the server commands in order to control these tasks as you see fit, but wouldn’t that be risky for the server? 

So, consider what WordPress does as a workaround in this situation. However, this has some drawbacks that we will examine in a while.

The WP-Crontrol Plugin

A great and easy way to view the list of cron jobs in your WordPress website, is to install the WP-Crontrol plugin. 

After activating it, you can view the plugin’s admin page under the Tools->Cron Events menu item. In a vanilla installation you will see something like this:

If you mouse-over each row, you will notice that there are provided actions for you to edit or run any of the events.

In the edit screen of the wp_update_themes event for example, you can modify its settings

Under the Settings -> Cron Schedules menu item, you can view the default schedules and if you want, add one of your own and give it a name to be viewed on the list.

How to Create a Cron Job

To add a cron job manually, all you have to do is edit the theme’s functions.php file. To demonstrate a simple example, open it with your favorite editor and add the following piece of code:

add_action( 'my_cronjob', 'my_cronjob_function' );

function my_cronjob_function() {
    wp_mail( 'EMAIL_ADDRESS', 'Test email', 'This is a test message' );
}

Where ‘my_cronjob’ is the name of your hook and ‘my_cronjob_function’ is the name of your function that will simply send an email to the address you defined by replacing EMAIL_ADDRESS with the desired one.

Next, we need to schedule this hook to be executed the time we want.

How to Run the Job Once

To perform the action as a one-time WP-Cron job, we have to use the wp_schedule_single_event() WordPress built-in function that is designed to trigger a hook at a specified time. It’s structure is like this:

wp_schedule_single_event( $timestamp, $hook, $args, $wp_error )

Where $timestamp is the Unix timestamp for when to next run the event and $hook is the action hook to execute when the event is run.

Both these parameters are required. Now let’s talk about the optional parameters.

With the $args parameter you can use an array containing arguments, to pass to the hook’s callback function. Each value in the array is passed to the callback as an individual parameter. The array keys are ignored.

The $wp_error parameter can be used to return a WP_Error on failure. Its default value is false.

The corresponding code in our functions.php file would be like this:

add_action( 'my_cronjob', 'my_cronjob_function' );

function my_cronjob_function() {
    wp_mail( 'EMAIL_ADDRESS', 'Test email', 'This is a test message' );
}

wp_schedule_single_event( time() + 3600, 'my_cronjob' );

At this point you should be able to see your custom task in the list.

How to Run the Job as a Recurring Event

What WordPress provides for this scenario is the wp_schedule_event() function which is structured like this

wp_schedule_event( $timestamp, $recurrence, $hook, $args, $wp_error)

The $timestamp parameter is the required Unix timestamp for when to next run the event, $recurrence is a string also required for how often the event should subsequently recur and $hook is the action hook to execute when the event is run.

The optional $args and $wp_error parameters are the same as before.

The code that runs the job with a recurrence of, let’s say, 1 hour is this:

add_action('my_hourly_cronjob', 'hourly_action');

function hourly_action() {
    wp_mail( 'EMAIL_ADDRESS', 'Test email', 'This is a test message' );
}

if (! wp_next_scheduled ( 'my_hourly_cronjob' )) {
    wp_schedule_event(time(), 'hourly', 'my_hourly_cronjob');
}

We used the wp_next_scheduled() function in an ‘if’ statement like you see above, in order to avoid duplicated events and ensure the task is not already scheduled before proceeding and running it.

We also used the ‘hourly’ label from the scheduled table under Settings -> Cron Schedules. If we wanted a different occurrence, let’s say every 45 minutes, we should first create a custom Cron Schedule named “45_minutes” and then use it in the code.

add_action('my_45_cronjob', 'my_45_action');
function my_45_action() {
    wp_mail( 'EMAIL_ADDRESS', 'Test email', 'This is a test message' );
}
if (! wp_next_scheduled ( 'my_45_cronjob' )) {
    wp_schedule_event(time(), '45_minutes', 'my_45_cronjob');
}

At this point you should be able to see your custom task in the list with the expected changes:

WP-Cron Drawbacks

The way WordPress handles cron jobs ensures the task will run but doesn’t allow you to specify when because, as we said, the check is done when a visitor loads a page of your website. 

If we relay cron jobs control on the users’ visit time, then it is possible that we have a negative impact on the website no matter the size of it or how popular it is.

Host your website with Pressidium

60-DAY MONEY BACK GUARANTEE

SEE OUR PLANS

In the case of a popular website, you will experience a great amount of traffic due to the simultaneous execution of a large number of tasks. This may consume your server’s resources and impact performance or even cause downtime of your website.

In the case of a small website, which means few visitors, the wp-cron will not be triggered so often, therefore some important cron jobs may be postponed for enough time to create side effects, like not taking enough backups, or delay updating some data that is counted on a cron job.

Disable WP-Cron

If the way WP-Cron handles cron jobs does not meet your requirements, and you need the tasks executed right on time, then you should disable WP-Cron and use a server-side cron service.

If disabling WP-Cron is not an option already provided by your hosting provider here is how you can do it yourself.

Open the wp-config.php file, located under the root folder of your installation, with your favorite editor and find the lines related to the database table prefix. Right after, insert this line:

//

/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wN0b9WQk_';

define('DISABLE_WP_CRON', 'true');

This is mandatory if you want to go with a more stable scheduler, like the Linux cron service in order to trigger wp-cron.php whenever suits you better.

A Server-Side Solution: The Linux Cron Service

At Pressidium, we use the Linux Crontab to trigger WP-Cron every 5 minutes. It is the right amount of time that ensures your scheduled jobs are executed on time and at the same time avoid overloading your WordPress website. This does not interfere with the WP-Cron scheduler, but only the triggering mechanism.

Conclusion

Hopefully this article helped you get familiar with WordPress Cron, what it is and how it works, and how to create your own schedules and tasks. Think twice though whether WP-Cron suffices for your requirements, before choosing other server-side solutions.

Host your Website with Pressidium!

View our price plans

Host your website with Pressidium

60-DAY MONEY BACK GUARANTEE

SEE OUR PLANS

Do you like this article?

Subscribe to our blog and get awesome WordPress content straight to your inbox.

SUBSCRIBE

OUR READERS ALSO VIEWED:

5 Tips to Help You Choose the Right Domain Name for Your WordPress Site

Choosing the right domain name for your WordPress website is super important. Check out our top tips to help you get it right!
Austin Andrukaitis
Austin Andrukaitis
7 min read

What to Include in Your WordPress Privacy Policy

Stumped on what to put in your WordPress privacy policy? This guide details everything you need, including key laws to follow.
Jessica Day
Jessica Day
10 min read

Top 5 Capabilities of WordPress Full Site Editing That Impressed Us

This guide will teach you all about the top five capabilities of WordPress Full Site Editing that will help you build & customize your website!
Grace Lau
Grace Lau
9 min read

Two Factor Authentication and WordPress

WordPress Two Factor Authentication - what is it and how do you enable it on your website? Find out in this article!
Tassos Antoniou
Tassos Antoniou
6 min read
SUBSCRIBE