Nicola Mustone

Happiness Lead @ Automattic



Scheduled Events and WordPress Cron Jobs

A clock

When I say scheduled events, I don’t mean the awesome party that you may want to sell on your site, no. The scheduled events I’m talking about are actually events that occur in WordPress.

An example would be a scheduled sale on WooCommerce, or a scheduled post in your blog that you want to publish in the future.

You can create such events also by yourself, for your theme or your plugin. Like I said before, WooCommerce uses scheduled events for sales, that’s a custom one. I used them to sync two different blogs with a plugin.

If you want to learn how to use scheduled events in WordPress, keep reading!

Scheduled Events vs. Cron Jobs

You should know the difference between a scheduled event and a cron job.
Usually, WordPress people call scheduled events simply WordPress Cron Jobs, and they are not totally wrong. But real cron jobs are a different thing.

Real cron jobs run at server level, and you can configure them on your host/machine. They are independent from your site and work regardless of how many people visits your site.

WordPress cron jobs instead, or scheduled events, are like cron jobs, but they run in WordPress. Like real cron jobs, they can run at predefined intervals, like every day, every week, etc.

The bad thing about them is that, since they rely on WordPress to work, people need to visit your site. If nobody is visiting your site WordPress does nothing, and so scheduled events won’t run.

Make Sure That Scheduled Events Always Run

There’s a way to make sure that your scheduled events run regardless of the visits on your site, and it’s by using robots to ping WordPress.

You can use services like UptimeRobot or pingdom to make sure that, at regular intervals, you receive a visit on your site.

This way scheduled events will always run, even if there are not real visits.

Create Scheduled Events

To create a scheduled event you need the WordPress function wp_schedule_event().

It accepts three parameters:

  • When to run the event for the first time;
  • The frequency of the event;
  • A hook name.

The first parameters is a timestamp indicating when you want the event to run for the first time.

The second parameter, is a string that indicates how often it should run. It can
be one of the following values: hourly, twicedaily, daily.

You can also add a custom interval, but I will explain how to do that in a different article.

The third parameter, is a custom hook name.

Write The Code

Let’s get our hands dirty with some code. In the example we will create a scheduled event that runs every day.

Create a folder in wp-content/plugins/ and name it example-scheduled-events. Then create a file inside of it named example-scheduled-event.php, open it and add this code at the beginning of the file:


<?php
/*
Plugin Name: Example Scheduled Events
Plugin URI: https://wordpress.org/
Description: This is an example plugin to learn how to use scheduled events
Version: 1.0.0
Author: Your Name
Author URI: https://yoursite.com
Text Domain: egse
*/
/**
* Schedule the event when the plugin is activated, if not already scheduled
* and run it immediately for the first time
*/
register_activation_hook( __FILE__, 'my_activation' );
function my_activation() {
if ( ! wp_next_scheduled ( 'my_hourly_event' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event' );
}
}
/**
* Hook the function to run every hour
*/
add_action('my_hourly_event', 'do_this_hourly');
function do_this_hourly() {
error_log( 'I\'m alive!' );
}
/**
* Clear the scheduled event when the plugin is disabled
*/
register_deactivation_hook( __FILE__, 'my_deactivation' );
function my_deactivation() {
wp_clear_scheduled_hook( 'my_hourly_event' );
}

view raw

functions.php

hosted with ❤ by GitHub

At the beginning of the file we write the headers of the plugin, or WordPress won’t see it.

Right after that, we create an activation hook that runs only once, when you activate the plugin. The function hooked will check if the event is already scheduled, and if it is not, it creates the event and schedules it to run every hour.

It also specifies a function to run for that event, which is right after the activation hook. It simply writes a sentence in the error log.

The last function clears the schedule when you disable the plugin and runs only once.

You can now activate the plugin to see how it works. Once active, check your site’s error log, you will find the message “I’m alive!” inside of it. Check it one hour later, and you will find the same message again, and so on every hour.

Debugging Scheduled Events

I usually debug code by using var_dump() and die() to see the output. This won’t work with scheduled events. Or better, it works, but you can’t see it.

The best way to debug scheduled events is to use error_log() instead, printing the output in the debug.log file in your wp-content/ folder.

Advertisements

Subscribe to This Blog

Receive new articles from this blog directly in your inbox! No spam guaranteed!

Join 651 other subscribers

Contribute to Improving This Blog

Did you enjoy this article? Was it helpful? Contribute to help me write more articles! The funds collected from this blog are reinvested directly into improving my skills or the blog so that I can provide more and better content!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

€5.00
€15.00
€100.00
€5.00
€15.00
€100.00
€5.00
€15.00
€100.00

Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly
Advertisements

More Posts That You Might Like…


4 responses to “Scheduled Events and WordPress Cron Jobs”

  1. Thanks for another good post on this WordPress topic. I was not able to locate parts 1 and 2 of this series.

    1. You’re welcome Amit!

      One of the other posts in this series is not published yet, it will on the 1st Jan.
      You can find the other two by clicking on their title in the series box at the top of this article.

  2. I have setup the cron job at every 3 hours. I wanted to run this cron job at any time by manual triggering. WP is not allowing to call the cron until next clock 3rd hour come. How can I call the cron regardless of interval?

    1. Hello,
      You can use the plugin WP Crontrol to have a management page for all the cron jobs on your site. It also has tools to run a specific cron job whenever you want.

Leave a Reply

Advertisements

Categories

Newsletter

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Join 651 other subscribers

About The Author

Hi, I’m Nico! Support Lead at Automattic, championing WordPress.com & WooCommerce. Off-duty, I’m at Elemental Beacon, leading epic D&D adventures. Let’s connect, whether it’s about WordPress or a quest!

Advertisements

Don't Miss a Thing!

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Join 651 other subscribers

Continue Reading

%d bloggers like this: