How to Use WP-Cron to Run WordPress Cron Jobs

Scheduling tasks to be run at regular intervals in your WordPress plugin can be confusing if you’ve never done it before. And testing to make these “WordPress cron jobs” work properly can be challenging as well, since you can’t see output from the job code as easily. Or at least, that is the experience I had when developing cron jobs for my AI Chat plugin for WordPress. Let me show you how I used WP-Cron to schedule tasks in my WordPress plugin, and how I tested them to make sure they worked properly.

WP-Cron to Run WordPress Cron Jobs Cover Image

What is WP-Cron?

WP-Cron is a task scheduling system that is built into WordPress that enables the site to perform time-sensitive tasks. Simple tasks might include publishing scheduled posts, checking for updates, or sending emails.

WP-Cron is not a perfect scheduling system. Because many WordPress sites are on shared hosting, and the hosting environments for different installations can be very different, WordPress cannot use terminal utilities to guarantee the running of WordPress cron jobs at an exact time.

Instead, every time a page load occurs, a non-blocking request is sent to run wp-cron.php, which checks if there are any tasks that are due to be run, and if there are, it runs them. This means that if a job is due to be run at 8pm, but a page load does not occur until 9pm, then the job will not be run until then. Once a job is run, it can be rescheduled again based on an interval, allowing tasks to be run roughly once every 24 hours, or 7 days, etc.

At the end of this post, I will show a way to integrate WP-Cron with system cron to ensure that jobs are run on time. Stay tuned for that!

Implementing a Job

Register a Hook

The first step in scheduling WordPress cron jobs with WP-Cron is to schedule an event with the built-in scheduling functions. First, we need to hook into a hook like the init hook. Then, we check if our event is scheduled. If it is not, we schedule it:

add_action( 'init', function(){
    if (!wp_next_scheduled('cron_job_id')) {
        wp_schedule_event(time(), 'daily', 'cron_job_id');
    }
} );

This code checks if the event with id cron_job_id (you configure this with something unique) is scheduled to run. If it is not, it schedules it to run next at the current time, and every minute thereafter.

If you wish for your task to run in the future, you should simply replace the call to time() with a function that returns a future timestamp. For the second parameter, which defines how often to repeat the job, there are several options built into WordPress, including every_minute, hourly, daily, and more. You can also define your own custom schedules. Click here to learn how to do that.

Hook a Callback In

Now that we’ve got our event scheduled, we need a way to define what happens when it runs. Doing this is simple. All you have to do is hook into the event using the value you defined for the job identifier and pass a callback. In my example, this is identifier is cron_job_id.

add_action( 'cron_job_id', function(){
    //code that you want to run on an interval here
    //we will publish all posts that are drafts as an example
    $posts = get_posts(array(
        'post_type' => 'post',
        'post_status' => 'draft',
        'posts_per_page' => -1
    ));


    //publish the posts
    foreach ($posts as $post) {
        wp_publish_post($post->ID);
    }
} );

This callback will publish all posts that are in the draft status once a day (assuming the site is loaded often enough). But, you can replace the callback to make anything happen you want on the designated interval.

Testing WordPress Cron Jobs

An important part of plugin development is testing, especially if you want other people to use your plugin. But, testing WP-Cron jobs can be challenging because you need to wait for the job to run. And when it does, the background nature of the job makes it hard to capture output to diagnose issues.

Luckily, there are some useful tools that make testing WP-Cron jobs easier.

WP Crontrol

The first of these is the WP Crontrol Plugin. It adds a handy entry “Cron Events” under the “Tools” menu on the WordPress admin. On that page, it shows a table of all WordPress cron jobs, when they are going to run next, the interval they run on, the callback they will run, and much more. This plugin is well worth installing while developing a plugin, since it allows you to delete events and run them using a simple gui.

WordPress CLI

WP-CLI is another useful tool for testing WordPress cron jobs. It adds terminal commands that let you view the status and schedule of WP-Cron jobs, and run them from the command line. Here are some useful commands to get you started:

wp cron event run --due-now

Run all WP-Cron jobs that are due to be run.

wp cron event run --all

Run all WP-Cron jobs, whether they are due or not.

 wp cron event list

List all scheduled WP-Cron jobs.

There are other useful commands for exploring and managing jobs. Check the docs to see them all.

Running with Crontab

As I mentioned before, WP-Cron is not a truly perfect job scheduler. It does not guarantee a job will be run exactly every 24 hours, for example, because it relies on site visits to kick off the event running loop. We can, however, use the system cron on linux systems to guarantee WP-Cron runs tasks on schedule. All you need to do is access your system crontab using

crontab -e

and add an entry to run WP-Cron in there. System cron, unlike WP-Cron, ensures that tasks will be run exactly on time. We can use it to kick off WP-Cron jobs that are due using WP-CLI by adding the following line to the crontab:

* * * * * wp cron event run --due-now --path=/path/to/wordpress/installation

This will use system cron to run all due WP-Cron jobs every minute. Adjust your interval as needed.

If you use WP-CLI, it is recommended to restrict using page loads to kick off WP-Cron. To do this, add this line to your wp-config.php file:

define('DISABLE_WP_CRON', true);

Of course, you may not be able to install WP-CLI to your server. No problem! In that case, just trigger WP-Cron with an http command (like curl or wget) to the /wp-cron.php?doing_wp_cron path on your site like so:

*/10 * * * * curl -s http://your-site.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

Conclusion

Now, you know how to use WP-Cron to schedule WordPress cron jobs. This is a useful skill, especially as you build more complex plugins that run time and resource-intensive tasks. For more detail about using WP-Cron, check the docs here. Thanks for reading my guide. Best of luck in your WordPress plugin development ventures!

Newsletter

📧 Sign up to receive updates when I create new content!

Comments

Leave a Reply

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