- A website analytics plugin should be able to generate a weeklyreport on site usage statistics, and then send an email to the websiteadministrator.
- An email newsletter plugin might need to deliver emails on serverswhere there are hourly sending limits. The plugin would have to queueoutgoing emails and send a given number each hour.
- A chart image generator can gather data from a database, generatethe image, and save it to a cache instead of generating it on everyrequest—this will avoid unnecessary load on the database.
- A backup plugin will need a function to be activated once everyweek, so that it can generate the database backup and send an email tothe website administrator.
- A membership website plugin would require the ability to expiresubscriptions at the end of a month.
- A Twitter sidebar widget plugin that makes a request to theTwitter service only once an hour to fetch and load your latesttweets.
fsockopen
PHP functionto make a request to the wp-cron.php
file that’slocated in the WordPress installation directory. To make sure that thewebsite visitor is unaffected by this call, the timeout for the request isvery small (0.1 seconds). Having initiated the request, WordPress doesn’twait for a response, and continues serving the page to the user. The 0.1second timeout is enough to initiate execution of thewp-cron.php
file.The first statement the wp-cron.php
fileexecutes is:ignore_user_abort(true);This ensures that execution continues, even if the client whorequested the page closes the connection (this would otherwise terminateexecution). This script will check for any tasks that should be run, basedon the current time and the time they were last executed. For example,let’s say you have a task that’s scheduled to run hourly, and was last runat 4:13 p.m. When a user requests a page from your site at 5:11 p.m.,
wp-cron.php
will skip your task, as it was last runless than an hour prior. A few minutes later, at 5:15 p.m., when anotheruser views a page, wp-cron.php
will run yourtask.wp_head
function, which you’re probablyfamiliar with. Inside that function you’ll find this line ofcode:do_action('wp_head');The
wp_head
function is called within the<head>
section of theheader.php
file in a WordPress theme. When thatfunction is called, the above line of code will trigger the execution ofany functions that have been linked to the wp_head
action hook. It’s important to distinguish between thewp_head
method and thewp_head
action hook: they have the same name but aredistinct.If we want to add a style sheet to all pages without editing theheader.php
file, we simply create a function of ourown that generates the desired <link/>
tag, and then attach this function to the wp_head
action. The code below does this://This function generates the link tagfunction myplugin_generatestylesheet(){ //Form the URL to the css file stored in our plugin directory $pluginURL = get_bloginfo('home').'/wp-content/plugins/myplugin/mycss.css'; //Write it to the browser echo '<link href="'.$pluginURL.'" type="text/css" rel="stylesheet" />';}//Now we add this function to the wp_head action.add_action('wp_head','myplugin_generatestylesheet');The
add_action
function is the key here:it attaches our myplugin_generatestylesheet
function to the wp_head
action hook. Now, when thewp_head
method callsdo_action('wp-head')
, our function will be called,and the link tag will be output.You can define your own actions and add as many functions to thataction as you’d like. This turns out to be the key to WordPress’sscheduling functionality, as we’ll see shortly.- One-off task—a task that is to be executed once at a specifiedtime
- Recurring task—a task that’s executed at regularintervals
wp_schedule_single_event
function.First, we define the function that we want to schedule:function my_function(){ // Do something. Anything.}Next, we add this function to our action hook. Wait, we need tocreate the action hook first, right? Wrong. It turns out we don’t. Justadding the function to an action with a new name creates the new action.So, in this step, we create both the
my_action
action, and add the my_function
function tothat action:add_action('my_action','my_function');Finally, we schedule the action hook to run at the desiredtime:
wp_schedule_single_event($timestamp,'my_action');In the above line of code,
$timestamp
is thetime we want the action to run, formatted as a Unix timestamp.wp_schedule_event
function. The stepsinvolved in defining a recurring task are otherwise very similar to thesteps for a one-off task. Again, we start by defining a functioncontaining the code we want to execute periodically:function my_periodic_function(){ // Do something regularly.}We add the function to the new action hook:
add_action('my_periodic_action','my_periodic_function');Finally, we schedule the action to be executed with the desiredfrequency:
wp_schedule_event($timestamp, 'hourly', 'my_periodic_action');This function takes a new parameter: the frequency(
'hourly'
in the above example).$timestamp
is the time when the action hook shouldfirst be run, after which it will be run at a frequency determined bythe second parameter. The final parameter, as withwp_schedule_single_event
, is the action hook toschedule.WordPress defines three recurrence frequencies: hourly, daily, andtwicedaily. However, should you need a different frequency, never fear! Youcan define your own recurrence frequencies.cron_schedules
filter:add_filter('cron_schedules','my_cron_definer'); function my_cron_definer($schedules){ $schedules['monthly'] = array( 'interval'=> 2592000, 'display'=> __('Once Every 30 Days') ); return $schedules;}With this done, we can now use the new frequency when calling
wp_schedule_event
:wp_schedule_event(time(),'monthly','my_action');This will call
my_action
once every 30 days,starting from the current time.wp_clear_scheduled_hook
function should beused. The syntax couldn’t be simpler:wp_clear_scheduled_hook('name_of_hook');
wp_unschedule_event
function. Using thisfunction is less straightforward than the unscheduling of recurringevents.The syntax is as follows:wp_unschedule_event($timestamp, $hook, $arguments);Here, the
$timestamp
argument is the time whenthe event is scheduled to run. As you may be unaware of when the actionhas been scheduled to run, you can use thewp_next_scheduled
function to fetch the time,and then pass that intowp_unschedule_event
:$whenNext = wp_next_scheduled('my_action');wp_unschedule_event($whenNext,'my_action');
<?php /* Plugin Name: My Plugin Plugin URI: https://www.sitepoint.com/ Description: A plugin to learn crontasks. Version: 2.9.2 Author: Raj Sekharan Author URI: http://www.krusible.com *//* The activation hook is executed when the plugin is activated. */register_activation_hook(__FILE__,'myplugin_activation');/* The deactivation hook is executed when the plugin is deactivated */register_deactivation_hook(__FILE__,'myplugin_deactivation');/* This function is executed when the user activates the plugin */function myplugin_activation(){ wp_schedule_event(time(), 'hourly', 'my_hook');}/* This function is executed when the user deactivates the plugin */function myplugin_deactivation(){ wp_clear_scheduled_hook('my_hook');}/* We add a function of our own to the my_hook action.add_action('my_hook','my_function');/* This is the function that is executed by the hourly recurring action my_hook */function my_function(){ //do something.}?>
- Be aware that it’s not 100% precise
- For those of you accustomed to system-based cron jobs, oneobvious disadvantage of the WordPress scheduling API is that it’simpossible to ensure that the action you scheduled will run at anexact time. Although the scheduled functions will definitely beexecuted, they may run a little later than you’d like them to. Thisis because WordPress relies on website traffic to triggertasks.In cases where a website may lack adequate traffic, ascheduled task might not execute at the proper times. While anaction was scheduled to run at 12 a.m., it may actually run at 12:45a.m., because no one visited the website that late at night.
- Use appropriate frequencies
- Some time ago, I created a plugin that generated some contentpages for a blog by querying the Yahoo Search web service and theTwitter web service. The script was scheduled to run every fiveminutes. I wrote the plugin and configured it to run on myblog.The next day, my web hosting account was temporarily suspendedfor using excessive resources. It turned out that the scriptsometimes ran for far more than five minutes. This meant that a newtask would often start before the previous one had completed; aftercouple of hours there were 12 instances of the script running. Soonthere was no more memory left over for any other process, and thescript started to affect other website owners on the shared hostingserver. The lesson here is that you should ensure that you choosethe recurrence interval for your resource-consuming procedurescarefully.
- Use flags when using shared resources
- Scheduled tasks will often make use of the file system, orcertain database tables. Simultaneous access or operations on theseresources can corrupt or destroy the integrity of the data. This canhappen when your plugin has two or more tasks that rely on the samedata file or database table. Be sure to use read/write locks toprotect access to your resources.
Frequently Asked Questions about WordPress Scheduling
What are the best WordPress scheduling plugins available?
There are numerous WordPress scheduling plugins available, each with its own unique features and benefits. Some of the most popular ones include Bookly, WP Simple Booking Calendar, and BirchPress. Bookly is a responsive appointment booking tool that offers a sleek interface and a wide range of features. WP Simple Booking Calendar is a user-friendly plugin that allows you to create and manage booking calendars. BirchPress is a comprehensive booking solution that offers features like email notifications, customizable booking forms, and the ability to accept online payments.
How do I install a WordPress scheduling plugin?
Installing a WordPress scheduling plugin is a straightforward process. First, navigate to your WordPress dashboard and click on ‘Plugins’. Then, click on ‘Add New’ and search for the plugin you want to install. Once you’ve found it, click ‘Install Now’ and then ‘Activate’. The plugin should now be ready to use.
Can I customize my booking form with a WordPress scheduling plugin?
Yes, most WordPress scheduling plugins allow you to customize your booking form. This can include changing the layout, adding or removing fields, and customizing the color scheme. Some plugins also offer advanced customization options, such as conditional logic and multi-step forms.
Can I accept online payments with a WordPress scheduling plugin?
Yes, many WordPress scheduling plugins offer the ability to accept online payments. This can be done through a variety of payment gateways, including PayPal, Stripe, and Authorize.net. Some plugins also offer the ability to accept payments directly through the booking form, providing a seamless experience for your customers.
How do I manage bookings with a WordPress scheduling plugin?
Managing bookings with a WordPress scheduling plugin is typically done through the plugin’s dashboard. Here, you can view all upcoming bookings, confirm or cancel bookings, and manage customer information. Some plugins also offer features like automatic email notifications and the ability to sync bookings with your Google Calendar.
Can I use a WordPress scheduling plugin to manage multiple locations?
Yes, some WordPress scheduling plugins offer multi-location support. This means you can manage bookings for multiple locations from a single dashboard. This can be particularly useful for businesses with multiple branches or for individuals who offer services in different locations.
Are WordPress scheduling plugins mobile-friendly?
Yes, most WordPress scheduling plugins are designed to be mobile-friendly. This means that your customers can make bookings from their smartphones or tablets, providing a convenient and user-friendly experience.
Can I integrate a WordPress scheduling plugin with other tools?
Yes, many WordPress scheduling plugins offer integration with other tools. This can include email marketing platforms, CRM systems, and social media platforms. This allows you to streamline your workflows and manage all aspects of your business from one place.
Do WordPress scheduling plugins offer customer support?
Yes, most WordPress scheduling plugins offer customer support. This can include email support, live chat, and a knowledge base with helpful articles and tutorials. Some plugins also offer premium support options for an additional fee.
Are there free WordPress scheduling plugins available?
Yes, there are free WordPress scheduling plugins available. However, these often come with limited features and may not offer the same level of support as paid options. If you’re running a business, it may be worth investing in a premium plugin to get access to more advanced features and better support.
Raj is a freelance web developer who specializes in developing and customizing WordPress blogs. He is the creator of the WP Responder WordPress plugin.