WordPress Plugin Development Tutorial Manual - Task Plan WP Cron
Cron is a time-based task scheduling system that can be used on Unix systems. WP-Cron is a time-based task scheduling system that handles tasks in WordPress, and is used for several of WordPress's core features such as checking for updates and customizing the publishing functionality.
WP-Cron works by checking the list of scheduled tasks for tasks that need to be run while the page is loading, and the scheduled tasks will be executed when the page loads.WP-Cron does not run the same way as Cron on Unix systems, in that it is only triggered when the page loads. If we schedule a task to run at 2:00 PM and no page load occurs before 5:00 PM, the scheduled task will not run.
Why use WP-Cron
Why use WP-Cron? Many web hosts don't allow users to access the system Cron, but the WordPress core and many plugins require a Cron system to perform time-based tasks.Cron is a very useful tool, so WordPress provides a time-based WP-Cron system triggered by page loads. While the system doesn't necessarily run at a specific time, WP-Cron also has some chance of completing our scheduled tasks. Using the WordPress API to set up a Cron task is easier than setting it up any other way outside of WordPress.
If a task on a Unix system doesn't run at a specific time, he'll never run it. Instead, WP-Cron will execute tasks that expired and didn't run on the next page load, regardless of how long the task has been expired. Tasks will remain in the queue until a page load triggers them, so scheduled tasks set by WP-Cron will not be lost.
Understanding WordPress Task Plans
Unlike the Unix system Cron, which runs at a specific time (for example, the fifth minute of each hour), WP-Cron uses time intervals to simulate the system Cron by first giving the first task a run time, then setting a time interval in seconds, and then repeating the task at that interval. For example, we schedule a scheduled task that starts at 2:00 PM with a 300-second (5-minute) interval, which first runs once at 2:00 PM, then at 2:05 PM, and then every 5 minutes.
To simplify scheduling tasks, WordPress provides three default intervals and an easy way to add custom intervals. We can create a filter to add custom intervals such as:
add_filter( 'cron_schedules', 'example_add_cron_interval' ).
function example_add_cron_interval( $schedules ) {
$schedules['five_seconds'] = array(
'interval' => 5, 'display' => esc_html
'display' => esc_html__( 'Every Five Seconds' ),
);
return $schedules.
}
This filter function creates a new time interval that allows us to run the Cron task every 5 seconds.
Scheduling WP Cron Events
Planned cyclical missions
In order for our task to execute, we need to create a custom hook and mount a callback function to this hook, this is a very important step, forget this step and our task plan will never be executed.
In the following example, we will create a hook, the first parameter is the name of the hook, and the second parameter is the name of the callback function mounted to the hook.
add_action( 'bl_cron_hook', 'bl_cron_exec' );
Now, let's do the actual task scheduling. Another thing to keep in mind is that WP-Cron is rather simple in scheduling tasks, there is no de-duplication, the tasks are driven by the hooks provided for the task, but if multiple calls are made to the wp_schedule_event() If we use the same hook name, the task will be called multiple times. If our code executes the task when every page is present, it could result in the task being executed many times, which is not a good idea. wordpress provides a wp_next_scheduled() functionto help us check if a particular task has been scheduled.
wp_next_scheduled() takes one argument - the name of the hook - and returns a string containing the timestamp of the next execution, or false is used to indicate that the task is not scheduled, and is used as follows:
wp_next_scheduled( 'bl_cron_hook' );
We use wp_schedule_event() to accomplish repetitive task scheduling, which takes three required arguments and one additional argument. We can use the additional argument to pass an array to the callback function that executes the WP-Cron task. We will focus on the first three parameters, which are listed below:
- $timestamp - Unix timestamp of the first time this task was performed
- $recurrence - name of the recurrence interval for performing the task
- $hook - name of the custom hook used to call it
We'll demonstrate this using a 5 second interval and the hook we created earlier:
wp_schedule_event( time(), 'five_seconds', 'bl_cron_hook' );
Remember, we need to first make sure that the task plan has not already been scheduled, the full code is below:
if ( ! wp_next_scheduled( 'bl_cron_hook' ) ) {
wp_schedule_event( time(), 'five_seconds', 'bl_cron_hook' );
}
Cancel task plan scheduling
When we no longer need a particular scheduled task, we can use the wp_unschedule_event() functionto cancel the task plan scheduling, this function has two arguments:
- $timestamp - timestamp of the next task
- $hook - the name of the custom hook used to invoke the
This function can cancel not only scheduled tasks executed at each timestamp, but also all future recurring task schedules. If you don't know the timestamp of the next task, you can use the wp_next_scheduled() function lookup, which takes one argument:
- $hook - the name of the custom hook used to invoke the
Putting the above code together, it should look something like the following.
$timestamp = wp_next_scheduled( 'bl_cron_hook' );
wp_unschedule_event( $timestamp, 'bl_cron_hook' ).
When we no longer need certain task plans, it's important to cancel them in a timely manner because WordPress will continue to try to execute them. The important time to cancel scheduled tasks is when the plugin is disabled, and many plugins in the WordPress.org plugin directory forget this and fail to clean up task plans that are no longer needed on their own. If you find a plugin that does this, try contacting the plugin author to update their code.WordPress provides us with a plugin named register_deactivation_hook() function, which allows developers to run a function when the plugin is deactivated, is very simple to set up, the example is as follows:
register_deactivation_hook( __FILE__, 'bl_deactivate' ).
function bl_deactivate() {
$timestamp = wp_next_scheduled( 'bl_cron_hook' ); function bl_deactivate( __FILE__, 'bl_deactivate' ); function bl_deactivate()
wp_unscheduled_event( $timestamp, 'bl_cron_hook' );
}
Mounting WP-Cron to the system task scheduler
As we described above, WP-Cron's execution is dependent on page loads and may not always run on a strictly regular basis, which can be a problem if we have critical tasks that need to be executed on time, fortunately, we have a simple solution to avoid this problem. Simply set the system's task scheduler to run at the intervals (or at specific times) we need. The easiest solution is to use a tool that sends a web request to the wp-cron.php file.
With task scheduling on our system, WordPress will no longer need to run the task schedule for us on every page load, and we can disable it to save on this unnecessary server overhead. WP-Cron can be disabled by setting a constant in wp-config.php, adding the following to wp-config.php in wp-config.php.
define('DISABLE_WP_CRON', true).
Windows system
In Windows, the time-based task system is called Task Scheduler, which we can find through "Administrative Tools" in the Control Panel. How you set up tasks varies depending on your server setup. One way is to use PowerShell and a basic task. After creating the basic task, you can use the following command to invoke the WordPress Cron script.
powershell Invoke-WebRequest http://YOUR_SITE_URL/wp-cron.php
Mac OS X and Linux
Both Mac OS X and Linux use Cron as a time-based scheduling system, and they can usually be accessed from a terminal using the following command.
crontab -e
It should be noted that the task will be run as either the regular user or the root user depending on the system user running the command. there is a specific syntax for Cron.
- minutes
- hourly
- Days in January
- dates
- Days of the week
- command that needs to be executed
When setting up a scheduled task, time periods that are not taken into account are replaced with the * symbol, e.g., if we need to run a command every 15 minutes without taking into account the hour, day, and month, the scheduled task is set up as follows:
15 * * * * * command
Many servers come with a wget utility that we can use to access WordPress Cron scripts.
wget http://YOUR_SITE_URL/wp-cron.php
The Unix Cron settings for the WordPress Cron that triggers the site every morning are as follows:
0 0 * * * * wget http://YOUR_SITE_URL/wp-cron.php
How to test WP-Cron in a simple way
In this tutorial, we will create a plugin that will run a task and display a message every 5 seconds. For testing purposes, we will load the wp-cron.php file directly in the browser and output the data to the browser. Otherwise we will need to perform some other operations, possibly manipulating the database, since scheduled task operations don't usually show output on the site. Let's quickly go through the initial steps to get this setup.
Create a plugin file
Create a folder "my-wp-cron-test" and a file "my-wp-cron-test.php" in the wp-content/plugins folder. Of course, you can use other names as well. Open the PHP files we just created and start editing:
<?php
/* /* /* /* /* /* /* /* /* /* /* /*
Plugin Name: My WP-Cron Test
*/
The code above sets the name that will be displayed on the WordPress plugin page, don't forget to enable the plugin.
test code
Open the YOUR_SITE_URL/wp-cron.php page in your browser.
View all currently scheduled tasks
WordPress has an undisclosed function _get_cron_array which returns an array of all current scheduled tasks, we will use the var_dump function to output all scheduled tasks. Add the following code to the plugin:
echo ''; var_dump( _get_cron_array() ); echo '
';
Put it into an easy to call function as follows:
function bl_print_tasks() {
echo ''; var_dump( _get_cron_array() ); echo '
';
}