Wp Cron

WordPress has its own cron system implementation. It works right after installation and does not need any additional server configuration. It sends a HTTP request on every page request of your website to wp-cron.php and executes scheduled events of the core and plugins.

In this article we are going to see how to use WordPress Cron or WP Cron to register custom cron schedules and cron events.

  1. WP-Cron is important. So make sure it keeps working. Think of this plugin as insurance, but free. WordPress, plugins, themes, and servers are all moving parts that can be updated at anytime.
  2. By default the WordPress tasks that have been set up to run with wp-cron.php only run when a WordPress page is visited by a user, if the site has low traffic then tasks make take a while to action, if the site is high traffic and has caching then this can also cause reliability issues, instead you can manually set up the cron tasks to run at a.
  3. Before actually taking a look at WordPress cron jobs, it’s important to understand exactly what a cron job is. Simply put, a cron job is a task that is set to run at a specified interval. Generally speaking, it’s available on Linux or Unix-based system (OS X included) and, thus, most web hosts.

You are going to learn:

  • Test WordPress Cron Events?

See all WordPress Cron schedules? See all WordPress Cron schedules?

We can use the function wp_get_schedules() which show all the exiting schedules something like below:

View this gist on GitHub

Add WordPress Cron Schedules Add WordPress Cron Schedules

In WordPress we have a filer cron_schedules which allow us to add custom schedule.

We have see we can use the function wp_get_schedules() to see all the existing schedules.

In above example we have below schedules:

  • hourly
  • twicedaily
  • daily
  • weekly

But, We can use the cron_schedules to add our own custom schedules. Let’s add a every_ten_minutes schedule to perform some action.

View this gist on GitHub

Here, We have added a new schedule with 600 seconds interval means for every 10 minutes.

Add WordPress Cron Event Add WordPress Cron Event

We have register the custom schedule every_ten_minutes for every 10 minutes.

Now, Lets add the a custom schedule event or cron event.

We can register the schedule event with function wp_schedule_event().

See below code snippet:

View this gist on GitHub

Here, We have register the prefix_cron_hook schedule event. This scheduled event trigger for every 10 minutes.

But, We have to add a action which is same as our scheduled event.

We can use the same action prefix_cron_hook to perform some task. So, Lets add a sample task.

Add WordPress Cron Task Add WordPress Cron Task

We can use the function add_action() to perform our scheduled event with hook prefix_cron_hook.

See below code for reference:

View this gist on GitHub

Here, We have used function error_log() into our scheduled event task. So, Wherever our event prefix_cron_hook event trigger (every 10 minites) then our hook prefix_cron_hook called.

And our function prefix_cron_task() called which is hooked in action prefix_cron_hook.

In short; the string Called is added into the debug.log file (if WP_DEBUG & WP_DEBUG_LOG is true from wp-config.php file)

Test WordPress Cron Events? Test WordPress Cron Events?

We have an amazing WordPress plugin called WP Crontrol. The plugin WP Crontrol provide a user interface in which we can see the all registered scheduled and events.

Install and Activate the WP Crontrol plugin from WordPress back-end (wp-admin) Install and Activate the WP Crontrol plugin from WordPress back-end (wp-admin)

Follow below steps to install the WP Crontrol plugin.

  • Go to Plugins > Add new
  • Search for WP Crontrol
  • Click on the Install now and then Activate button

See below screenshot for reference:

Install and Activate WP Crontrol with WP CLI Install and Activate WP Crontrol with WP CLI

Alternatively, If you have a WP CLI setup then you can install the WP Crontrol plugin with WP CLI command.

Use below command which install and activate the WP Crontrol plugin.

If installed but not activate then use blow command to activate the WP Crontrol with command line

See all WordPress Cron Schedules? See all WordPress Cron Schedules?

To see all the existing Cron schedules navigate to to Settings > Cron Schedules.

See below screenshot for reference:

Here, You can see our registered schedule every_ten_minutes which indicate the interval 600 seconds (Every 10 minutes).

See all WordPress Cron Events See all WordPress Cron Events

To see all cron event navigate to Tools > Cron Events.

See below screenshot for reference:

Here, You can see our scheduled event prefix_cron_hook which is recurrence (trigger for every) 10 minutes.

Manually Run the WordPress Cron Event Manually Run the WordPress Cron Event

Yes, The plugin WP Crontrol allow us to execute the Cron Event manually.

Just click on Run Now action link which appear blow the scheduled event on hover.

See below screenshot for reference:

Now, On click on Run now to and see the debug.log file which show you the string Called. You can see something below string:

See below screenshot for reference:

Here, For testing I have just used code error_log( ‘Called’ );. You can use your own task.

NOTE: In the debug.log file we cant see the logging data until we enable the debug log. We can use set constant DEBUG_LOG to true to enable the debug log.

A few weeks ago we talked about what “cron jobs” were in WordPress and beyond. That tutorial about what “WordPress scheduled tasks” are hopefully gave you a good understanding of some of the things that you might do with them. Today we’ll instead focus on how you’ll use wp_schedule_event to actually do them. That is, we’ll cover a number of WordPress cron job examples.

At a high level, these means that we’ll come to understand the wp_schedule_event function, and see how we can use it and few helpful other functions to use WP-Cron in a WordPress plugin. We’ll also briefly look at really useful WP cron plugin for finding out if/when your scheduled tasks for WordPress will run. Let’s get to it.

Refreshing our Understanding of WP Cron for Plugins (& more)

Before we get to our WordPress cron example, a quick overview. We call the general class of “solve scheduling of function calls” in the computer space to be about “cron.” This is why we often see people refer to the WordPress scheduling system as “WP-Cron” even though it’s member functions refer to WordPress “scheduled events.” They’re all about the same thing: scheduling things to happen on a WordPress site.

Wp Cron

To help make this concrete, here are a few things using wp_schedule_event on WPShout itself right now:

  • WordPress (core) cleaning up auto-drafts of posts that shouldn’t be kept any longer
  • Jetpack cleaning up its transients (temporarily cached variables) on a schedule more aggressive then WordPress’s.
  • WordPress (core) cleaning up transients
  • Yoast SEO scheduling some thing (I’m not sure what) called onpage_fetch to run weekly
  • Updraft Plus running backups to Dropbox

I could go on, or name a large number of other similar things. I think it gets you started to think about when and why you might want to reach for wp_schedule_event yourself. So let’s get to it, how do you use that function and others to schedule task running in WordPress.

The Main WordPress Cron Hook: wp_schedule_event

So first we’ll start to understand how to create a “WP Cron Job” by understanding that function signature of wp_schedule_event. It looks like:

So, those parameters in more detail:

  1. $timestamp is meant to be the first time you want the event to occur. So the most common value submitted here is the current time. You get that in PHP with the time() function.
  2. $recurrence is a string value saying when you want the event to run. By default WordPress expects the values hourly, twicedaily or daily. As we’ll show off in just a bit, you can make a wp_schedule_event registered events run on a different schedule than those three, but those are the most common by far.
  3. $hook will be the (name of the) function you want WordPress to call when your event runs. This is a string like 'updraft_backup' where your function is called updraft_backup.
  4. $args is any argument(s) that your $hook function will need to see when called. I’ve never used it, and we won’t see it in any examples, but it’s good to know you can pass them.

Making wp_schedule_event Daily Run Your Function

Now that we have a sense of how to call wp_schedule_event, let’s see it used in context to schedule a function we made up called wpshout_do_thing to run every day. In a plugin, that might look like:

Now, you can run your code which calls wp_schedule_event a bunch of ways. But one of the best ones is to tie it to a single-time event, like the plugin being activated. That’s what we’re doing here.

Then we’re making sure that an event for us is not already scheduled. We’ll go into more detail on this later, but this is a good practice just to make sure you don’t end up running your event a few different times because someone was, for example, trying out your plugin and deactivating it over-and-over.

Wp Cron Event

Clean Up After Yourself: wp_clear_scheduled_hook

If you’ve gone the path of rooting your scheduled task to the plugin being activated, you may also want to make sure that your task doesn’t cause an error if your plugin is turned off (deactivated). To do that, you can remove your scheduled event when they deactivate the plugin. That’d look like:

As you might have guessed, wp_clear_schedule_hook will just un-register the $hook or “task name” you’ve scheduled with a call to wp_schedule_event.

wp_schedule_event Daily at a Specific Time

Let’s say your website gets the least traffic at 3am. And so you want your backups not when the plugin is initially activated, but at a specific time. In this example code of wp_schedule_event, we’ll aim for 3am on your server. I’d do that like this:

The PHP function strtotime means “make this string into a time.”So it returns the same sort of value as time, but lets us use a more English-y phrase. So this task will first run at 3AM tomorrow morning and not right now. And then, because we’ve set the $frequency to 'daily', it should keep recurring every day at 3am. The downside to consider: if your users will have needed/wanted this to happen right away, you’ll want some other system to do that for them too. Which could be wp_schedule_single_event. But I want to cover another example before we get there…

wp_schedule_event every minute

So WP-Cron has a few really useful default intervals, but “every minute” isn’t one it offers. There are lots of reasons for this. Primarily these two:

  • Running at task every minute can add a lot of overhead on your server.
  • Running a task every minute is kind of at odds with the need-for-visits that makes WP-Cron a little unreliable for low-traffic sites. I talked a bit more about this in my introduction to WordPress scheduled tasks.

That said, there may be reasons that you want “every minute” or some other interval that WordPress doesn’t support for cron intervals out of the box. If you find yourself in that situation, this example code should help. First you must declare your interval:

So here the WordPress cron_schedules filter hook passes us an array of the interval it knows about. And we add to the passed array our interval, in this case I named it everyminute.

Then we just use wp_schedule_event, knowing that our interval, everyminute, exists (same as the stock daily one does):

This system is exactly what it looks like to make all kinds of custom intervals. If you’re a true chaos monkey, you could even do this (I don’t recommend it):

But that’d be making chaos in your WordPress cron schedules, so I don’t really recommend it.

Wp Cron Disable

WP Cron Not Working: Some conceptual prep

I’ve said it before and I’ll say it again: WP-Cron isn’t a “real” cron. It requires that your site gets visits onto which WordPress can tack the function-runs you’re scheduling. To that end, if WP-Cron isn’t working in the way you’d expect, you may need to “make WordPress cron into a real cron.” What that looks like is covered well in this little SiteGround tutorial.

Wp-cron Not Working

Other Powers, like How do I Schedule Once in WordPress?

So far we’ve mentioned a number of the major WP Cron functions, but I want to quickly run through the others that you may encounter or need to know in a bit more depth.

What’s wp_schedule_single_event?

Sometimes you’ll want your event or scheduled code to happen just once, and “not now.” So how do you schedule something to run once in WordPress? There’s a function called wp_schedule_single_event for that. As you might guess it lets you make a “WordPress cron job” that’s a one off.

As you might guess, it works pretty similarly to wp_schedule_event. wp_schedule_single_event is called just like this:

You’ll notice that this example code for wp_schedule_single_event looks familiar. What’s different? We lose the second “recurrence interval” that you’ll see on wp_schedule_event. Which makes perfect sense, because that _single_ in the name of the function makes it pretty clear that an $interval doesn’t really make sense. Other than that, everything is pretty similar in wp_schedule_event and wp_schedule_single_event code samples.

DISABLE_WP_CRON?

So let’s say you want WordPress to never run WordPress “cron jobs” when the page loads? That’s where the DISABLE_WP_CRON constant comes in. What it does is allow you to run the site’s cron jobs via a direct call (with cURL, a browser, etc) to example.com/wp-cron.php to do the tasks, but means that it’ll never add cron work to a page load. This’ll make page responses that might have been caught by a big cron task a whole lot faster.

To use it, you’ll put define( 'DISABLE_WP_CRON', true ); in your wp-config.php. But don’t do so unless you find some other way that WordPress can do cron jobs. If you just disable cron and don’t build a real cron job (on Unix, etc) to make up for it, scheduled tasks simply won’t run on your WordPress site.

Disable Wp Cron

What wp_next_scheduled does

We mentioned it earlier, but to recap wp_next_scheduled is a way that we can pass WordPress a name and it can tell us if or when that task will run next. This is super useful for us to not schedule a new event when there’s already another one scheduled for us. This is why our ideal way to use wp_schedule_event is like this:

Cron

Wp Crontrol

(Because the above WP-Cron code snippet is the same as before I’ll not really explain it.) Though it is worth noting that wp_next_scheduled will give us the (Unix epoch) time that a task will run if it was going to. So you could also use it to do something like this:

Now you might get a negative value if wpshout_do_thing isn’t scheduled. But I can see a few reasons you’d do this. Again, what this’ll do is get when your next task is scheduled (in seconds since Jan 1, 1970), and then subtract the current time.

More on wp_clear_scheduled_hook

Like above, we covered wp_clear_scheduled_hook a bit already. In short, it’s how you make sure that you’ve cleaned up after yourself and your WordPress plugin cron tasks. Newsmax twitter. So that relevant code snippet from above:

As I said, it just clears tasks. So please only use it on your own scheduled tasks, unless you really know what you’re doing.

See Scheduled Cron Jobs

A last important thing: how do I confirm that I’ve successfully used wp_schedule_event to schedule my task in WordPress?

As you might have discerned, wp_next_scheduled could be used to do this. But it’s not the easiest to use. Instead, I’ve used and appreciated a great deal the WP Crontrol plugin. As you might guess, it shows you all the relevant hooked things on your whole WordPress site. Which makes it pretty darn easy to control cron tasks, or just make sure that your WordPress cron example code has worked. 🤓

What We’ve Learned about wp_schedule_event and WP Cron Jobs in General

So hopefully with what we’ve covered today you’re pretty comfortable understanding WP cron jobs, how to schedule them, and a few more of the relevant variables and elements you need. wp_schedule_event is the heart of the WP Cron system. And simply WordPress sites wouldn’t work without them.