Mastering WordPress Cron for Scheduling Events
Key Takeaways
- WordPress Cron is a set of functions that enables scheduling of tasks on a WordPress site, running when a page is loaded. It is different from Unix’s Cron as it is not always on the lookout for new tasks, instead, it executes tasks upon page loading.
- There are two types of Cron events that can be scheduled: single events, which run once and never again until rescheduled, and recurring events, which run on a set schedule indefinitely. Both types require the creation of a custom ‘Action’ which must be registered with Cron.
- Un-scheduling events is essential, especially when using plugins, as WordPress will continue to attempt to run events even after a plugin is deactivated or deleted. To un-schedule an event, one needs to know the name of the hook and the next scheduled time for the Cron run.
- Custom Cron intervals can be set by hooking into the cron_schedules filter and adding a custom interval. This can be utilized when scheduling events using Cron.
WordPress Cron is one of the most useful features that you’ll want to learn and understand if, like me, you spend a great deal of time working with WordPress.

Being able to run certain functions on a tight schedule is essential for any CMS and WordPress has a set of functions which help make this process very simple and almost effortless.
In this article I will cover the following WordPress Cron features:- How is WordPress Cron different than your normal Cron
- Scheduling a recurring event
- Scheduling a single event
- Un-scheduling an event
- Specifying custom Cron intervals
What is Cron?
You are probably familiar with the term ‘Cron’ as it relates to the time-based scheduler in Unix systems and although WordPress’ Cron is different; the main idea behind it is the same.
Some examples of how WordPress is using it’s Cron system internally is checking for theme and plugin updates and even checking if there are posts ready to be published.
How is WordPress Cron Different?
If you are familiar with Unix’s Cron, you probably think that WordPress’ Cron is always on the lookout for new tasks and running them as they come. This is far from the truth and I’ll explain why shortly.
WordPress’ Cron runs when a page is loaded, whether it’s a front-end or back-end page. In other words, when a page is loaded on your website, WordPress will check if there are any tasks or events that need to run and execute them. If you are thinking this is not ideal, you are absolutely right.
If you happen to have a website that doesn’t get too much traffic and you have a task that needs to be executed at a precise time, WordPress will not know the task is due until someone visits your website. Even if it happens to be a search engine bot crawling your website.
Scheduling Events with Cron
There are two flavors of Cron events that you can schedule with a few lines of code:
- Single events – run only once and never again until it is rescheduled again.
- Recurring events – run on a schedule and is set to re-occur indefinitely using a time interval.
Scheduling a Recurring Event
Scheduling a recurring event requires that you create a custom ‘Action’ which must also be registered with Cron. Once the Cron runs, the function attached to the custom ‘Action’ you created earlier is executed.
Let’s take a look at the following example where we are going to be deleting post revisions on a daily basis.
First we create our custom ‘Action’ which will have attached to it the function we want to run when the hook is called by Cron.
<span><span><?php </span></span><span><span>// delete_post_revisions will be call when the Cron is executed </span></span><span><span>add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); </span></span><span> </span><span><span>// This function will run once the 'delete_post_revisions' is called </span></span><span><span>function delete_all_post_revisions() { </span></span><span> </span><span> <span>$args = array( </span></span><span> <span>'post_type' => 'post', </span></span><span> <span>'posts_per_page' => -1, </span></span><span> <span>// We don't need anything else other than the Post IDs </span></span><span> <span>'fields' => 'ids', </span></span><span> <span>'cache_results' => false, </span></span><span> <span>'no_found_rows' => true </span></span><span> <span>); </span></span><span> </span><span> <span>$posts = new WP_Query( $args ); </span></span><span> </span><span> <span>// Cycle through each Post ID </span></span><span> <span>foreach( (array)$posts->posts as $post_id ) { </span></span><span> </span><span> <span>// Check for possible revisions </span></span><span> <span>$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); </span></span><span> </span><span> <span>// If we got some revisions back from wp_get_post_revisions </span></span><span> <span>if( is_array( $revisions ) && count( $revisions ) >= 1 ) { </span></span><span> </span><span> <span>foreach( $revisions as $revision_id ) { </span></span><span> </span><span> <span>// Do a final check on the Revisions </span></span><span> <span>if( wp_is_post_revision( $revision_id ) ) { </span></span><span> <span>// Delete the actual post revision </span></span><span> <span>wp_delete_post_revision( $revision_id); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span><span>}</span></span>
For scheduling the recurring event we make use of the wp_schedule_event( $timestamp, $recurrence, $hook, $args ) function which takes 4 arguments:
- $timestamp — (integer) (required) The first time that you want the event to occur. This must be in a UNIX timestamp format. WP cron uses UTC/GMT time, not local time. Use time(), which is always GMT in WordPress. (current_time( ‘timestamp’ ) is local time in WordPress.)
- $recurrence — (string) (required) How often the event should reoccur. Valid values are ‘hourly‘, ‘twicedaily‘ and ‘daily‘. We’ll see how to create our own time intervals later.
- $hook — (string) (required) The name of an action hook to execute.
- $args — (array) (optional) Arguments to pass to the hook function(s).
First we make sure the event has not been scheduled before and if it hasn’t, we go ahead and schedule it.
<span><span><?php </span></span><span><span>// Make sure this event hasn't been scheduled </span></span><span><span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span><span>}</span></span>
Note that you can also add tie this snippet of code to an action. If you are a plugin writer, you could set up the scheduled event to run the first time the plugin options page is visited. For a much simpler example, we are going to tie it to WordPress’ init action.
<span><span><?php </span></span><span><span>// Add function to register event to WordPress init </span></span><span><span>add_action( 'init', 'register_daily_revision_delete_event'); </span></span><span> </span><span><span>// Function which will register the event </span></span><span><span>function register_daily_revision_delete_event() { </span></span><span> <span>// Make sure this event hasn't been scheduled </span></span><span> <span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span> <span>} </span></span><span><span>}</span></span>
Now that you know how to schedule recurring events, let’s take a look at creating a single event which will never run again until it is rescheduled.
Scheduling a Single Event
Just as its name suggests, a single event is one that runs once and then it stops. This single event can still be rescheduled again if needed.
The concept behind it is the same as the recurring events. First you register a custom hook which is called by Cron when it runs on the server. Once Cron calls the hook, its function is executed and that’s basically how you get things done.
As an example, we are going to be setting an expiration date for posts. Posts will expire 30 days after being published. We are going to be hooking into the publish_post so that we can schedule our single event as soon as the post is published and count down begins.
Setting up the function which will delete the post after 30 days.
<span><span><?php </span></span><span><span>// delete_post_revisions will be call when the Cron is executed </span></span><span><span>add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); </span></span><span> </span><span><span>// This function will run once the 'delete_post_revisions' is called </span></span><span><span>function delete_all_post_revisions() { </span></span><span> </span><span> <span>$args = array( </span></span><span> <span>'post_type' => 'post', </span></span><span> <span>'posts_per_page' => -1, </span></span><span> <span>// We don't need anything else other than the Post IDs </span></span><span> <span>'fields' => 'ids', </span></span><span> <span>'cache_results' => false, </span></span><span> <span>'no_found_rows' => true </span></span><span> <span>); </span></span><span> </span><span> <span>$posts = new WP_Query( $args ); </span></span><span> </span><span> <span>// Cycle through each Post ID </span></span><span> <span>foreach( (array)$posts->posts as $post_id ) { </span></span><span> </span><span> <span>// Check for possible revisions </span></span><span> <span>$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); </span></span><span> </span><span> <span>// If we got some revisions back from wp_get_post_revisions </span></span><span> <span>if( is_array( $revisions ) && count( $revisions ) >= 1 ) { </span></span><span> </span><span> <span>foreach( $revisions as $revision_id ) { </span></span><span> </span><span> <span>// Do a final check on the Revisions </span></span><span> <span>if( wp_is_post_revision( $revision_id ) ) { </span></span><span> <span>// Delete the actual post revision </span></span><span> <span>wp_delete_post_revision( $revision_id); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span><span>}</span></span>
Pretty simple, right? Now we need to schedule the event once the post is actually published. In order to accomplish this task we need to use the wp_schedule_single_event( $timestamp, $hook, $args ) function which takes 3 arguments.
- $timestamp — (integer) (required) The time you want the event to occur. This must be in a UNIX timestamp format.
- $hook — (string) (required) The name of an action hook to execute.
- $args — (array) (optional) Arguments to pass to the hook function.
Here is quick look at how all this actions and hooks are put together.
<span><span><?php </span></span><span><span>// Make sure this event hasn't been scheduled </span></span><span><span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span><span>}</span></span>
We are using some time constants that WordPress has in place to make our lives easier. For more information on these constants, you can go to “Using Time Constants“, but here is a quick overview:
- MINUTE_IN_SECONDS = 60 (seconds)
- HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS
- DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS
- WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS
- YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
Un-scheduling Events
Now that you know how to schedule recurring and single events, it’s also going to be useful to know how to un-schedule these events.
You might be wondering, why would you want to un-schedule events? There is a good reason, particularly if you include some sort schedule events in your plugins.
Crons are stored on the wp_options table and by simply deactivating and deleting your plugin. WordPress will still try to run your events even though said plugin is no longer available. Having said that, please make sure you un-schedule events properly within your plugin or custom implementation.
Un-scheduling Cron events is relatively easy, all you need to know is the name of the hook and when is the next scheduled time that particular Cron is supposed to run. We are going to be using wp_next_scheduled() to find when the next occurrence will take place and only then we can un-schedule it using wp_unschedule_event().
Considering our first example, we would un-schedule the event the following way.
<span><span><?php </span></span><span><span>// Add function to register event to WordPress init </span></span><span><span>add_action( 'init', 'register_daily_revision_delete_event'); </span></span><span> </span><span><span>// Function which will register the event </span></span><span><span>function register_daily_revision_delete_event() { </span></span><span> <span>// Make sure this event hasn't been scheduled </span></span><span> <span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span> <span>} </span></span><span><span>}</span></span>
Customizing Cron Intervals
It is possible to set custom Cron intervals which you can use when scheduling events using Cron. To do so, we just need to hook into the cron_schedules filter and add our own. Let’s take a look at adding a custom interval set to run every 10 minutes.
<span><span><?php </span></span><span><span>// delete_post_revisions will be call when the Cron is executed </span></span><span><span>add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); </span></span><span> </span><span><span>// This function will run once the 'delete_post_revisions' is called </span></span><span><span>function delete_all_post_revisions() { </span></span><span> </span><span> <span>$args = array( </span></span><span> <span>'post_type' => 'post', </span></span><span> <span>'posts_per_page' => -1, </span></span><span> <span>// We don't need anything else other than the Post IDs </span></span><span> <span>'fields' => 'ids', </span></span><span> <span>'cache_results' => false, </span></span><span> <span>'no_found_rows' => true </span></span><span> <span>); </span></span><span> </span><span> <span>$posts = new WP_Query( $args ); </span></span><span> </span><span> <span>// Cycle through each Post ID </span></span><span> <span>foreach( (array)$posts->posts as $post_id ) { </span></span><span> </span><span> <span>// Check for possible revisions </span></span><span> <span>$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); </span></span><span> </span><span> <span>// If we got some revisions back from wp_get_post_revisions </span></span><span> <span>if( is_array( $revisions ) && count( $revisions ) >= 1 ) { </span></span><span> </span><span> <span>foreach( $revisions as $revision_id ) { </span></span><span> </span><span> <span>// Do a final check on the Revisions </span></span><span> <span>if( wp_is_post_revision( $revision_id ) ) { </span></span><span> <span>// Delete the actual post revision </span></span><span> <span>wp_delete_post_revision( $revision_id); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span><span>}</span></span>
Conclusion
Using WordPress’ Cron couldn’t be any easier and it is a very nice and interesting tool which is sure to help you make your plugin more robust. Learning all these functions and putting them into practice with real world applications is the best way to master WordPress’ Cron for scheduling events.
Frequently Asked Questions about Mastering WordPress Cron
What is the difference between wp_schedule_event and wp_schedule_single_event?
Both functions are used to schedule events in WordPress. The wp_schedule_event function is used to schedule a recurring event, meaning it will run at regular intervals that you specify, such as hourly, daily, or twice daily. On the other hand, wp_schedule_single_event is used to schedule a one-time event that will run at a specific time in the future. It’s important to choose the right function based on whether you want your event to run once or repeatedly.
Why is my WordPress Cron job not working?
There could be several reasons why your WordPress Cron job is not working. One common issue is a problem with the server’s time settings. If the server’s time is not correctly set, it can cause scheduling issues. Another possible issue is a conflict with a plugin or theme. Some plugins or themes may interfere with the WordPress Cron system, causing it to malfunction. It’s also possible that there’s an error in your code. Make sure to thoroughly test your code and check your server settings if you’re having trouble with WordPress Cron jobs.
How can I test if my WordPress Cron job is working?
There are several ways to test if your WordPress Cron job is working. One method is to use a plugin like WP Crontrol, which allows you to view and control what’s happening in the WP-Cron system. Another method is to use debugging tools. By enabling WP_DEBUG in your wp-config.php file, you can see any errors that occur when your Cron job runs. You can also use the error_log function in PHP to log any errors to a file.
Can I schedule a WordPress Cron job to run at specific times?
Yes, you can schedule a WordPress Cron job to run at specific times. The wp_schedule_event function allows you to specify the time when the event should first occur, and the interval at which it should recur. The wp_schedule_single_event function allows you to specify the exact time when the event should occur.
How can I unschedule a WordPress Cron event?
You can unschedule a WordPress Cron event using the wp_unschedule_event function. This function requires two parameters: the timestamp of the event and the action hook to the function you want to unschedule. Once you call this function, the specified event will no longer occur.
What is a WordPress Cron action hook?
A WordPress Cron action hook is a unique identifier for your Cron event. When you schedule an event, you associate it with an action hook. Then, you can attach functions to this action hook, and they will be executed when the event runs. This allows you to perform specific actions at specific times.
Can I use WordPress Cron to schedule posts?
Yes, you can use WordPress Cron to schedule posts. WordPress itself uses Cron jobs to handle scheduled posts. When you set a post to be published at a future date, WordPress schedules a Cron job to publish the post at the specified time.
How can I view all scheduled WordPress Cron jobs?
You can view all scheduled WordPress Cron jobs using a plugin like WP Crontrol. This plugin provides a user-friendly interface where you can see all the scheduled events, their intervals, and their next run times. You can also use it to add, edit, or delete Cron jobs.
Can I run a WordPress Cron job manually?
Yes, you can run a WordPress Cron job manually. You can do this using a plugin like WP Crontrol, which allows you to run any Cron event immediately. This can be useful for testing and debugging purposes.
What is the difference between a WordPress Cron job and a real Cron job?
A WordPress Cron job is a pseudo-Cron job. It’s not a real Cron job because it doesn’t run at the server level. Instead, it runs when a page is loaded on your WordPress site. A real Cron job, on the other hand, is a task scheduled at the server level. It runs at specific times, regardless of whether anyone visits your site. While WordPress Cron jobs are easier to set up and use, real Cron jobs can be more reliable and precise.
The above is the detailed content of Mastering WordPress Cron for Scheduling Events. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.
