How To Setup A Cron in WordPress

Want to know the step-by-step instructions to set up WP Cron or Queue Job or Scheduler on your WordPress website? Then you are in the right place. Here you will learn, in how many ways you can set up a cron job in WordPress

Table of Contents

  1. What is cron
  2. In how many ways we can create cron jobs in WordPress?
  3. WP Cron (How to use WordPress native cron)
  4. How to use UNIX crontab for WordPress
    1. How to add wp-cron.php in crontab
    2. How to use the custom page to run a specific method
  5. Action Scheduler
    1. Check if the package exists
    2. Installation
    3. Usage

What is Cron?

cron is a Linux utility that plans an order or content on your worker to run naturally at a predetermined time and date.

Orders including cron are alluded to as "cron jobs". It can be extremely helpful to computerize redundant undertakings.

What are the different ways by which we can create cron jobs?

  1. WP Cron (Native WordPress Cron)
  2. Crontab
    1. wp-cron.php
    2. Custom page
  3. Action-scheduler (3rd party package developed by Automattic)

Throughout the whole course of this tutorial, we will be considering a scenario that we have an eCommerce store and we want to send the abandonment cart email to the leads who do not place the order.

For example, we have written a method in our active theme's functions.php like this and now we want to run this via cron

function wh_check_and_send_cart_abandonment_mail()
{
    # All the magic happens here, with all the logic of collecting the user with cart info and sending the email
}

1. WP Cron

WP-Cron is WordPress's implementation of cron, a unix system for running time-based operations. WP-Cron removes the need for third-party developers to worry about complex cron implementations on different operating systems.

WP-Cron operates by processing any events that are scheduled for that period or are waiting from before that time when the page loads. This means that on a low-traffic site, operations will not take place at the planned time. The page load is the initial stimulus, and all subsequent waiting events are triggered by it.

2. Crontab

The crontab command on Unix-like operating systems allows you to edit the cron table. The cron table contains a list of activities that are scheduled to operate at regular intervals on the machine.

Cron refers to the daemon that reads the crontab and executes the commands at the appropriate time. It takes its name from Kronos, the Greek god of time.

Syntax to view list of all cron

crontab -l

And if you want to edit the file then you can use this command

crontab -e

2.1.  wp-cron.php

Two major disadvantage of WP-Cron are

  • Cron might not run on the specific or intender time on a website with lower traffic.
  • As the cron gets triggered on every page load and if you have lots of automation going on in the background then the page load speed might get hamper.

So to overcome this we can disable wp-cron altogether on every page load and instead add the cron URL in crontab.

To disable WP-Cron write the below line in wp-config.php

define('DISABLE_WP_CRON', true);

Add the below line in your crontab

*/5 * * * * curl -request GET ‘https://WEBSITE_URL/wp-cron.php’

Or if curl package is not installed then you can use this as well

*/5 * * * * wget -quiet -O - ‘https://WEBSITE_URL/wp-cron.php’ >/dev/null 2>&1

The above cron will execute at every 5min if you want to schedule at a different interval then you can tweak it accordingly. For more information, you can visit this site crontab.guru

2.2. Custom page

If you do not want the WordPress Version of cron altogether and instead wants your method to being executed via a specific page then you can create a custom page template in your active theme directory or your active child theme directory with the below code

<?php

/**
* Template Name: My Custom Cron Page
*
* @package THEME_NAME Child
* @subpackage Template
*/

wh_check_and_send_cart_abandonment_mail();

After creating the above page now either create a new page or edit an existing page in the WordPress page section and assign the above template from Page Attributes > Template. Like this

how to assign custom template in wordpress
Assign custom template to a page

Now when you will access the page it will trigger your method of cart abandonment. Now you just need to add this URL in your crontab like this

*/5 * * * * curl -request GET ‘https://WEBSITE_URL/my-cron-page

3. Action-scheduler

Action Scheduler was created to address the scaling problems caused by WP-Cron. The Action Scheduler generates processing queues for activities. Action Scheduler uses two approaches to process this queue. It would use its own WP-Cron case to attempt to process the queue every minute. It will also search for pending activities at the end of each WP-Admin request once per minute. Pending events that are due are processed in the background when either of these methods is called. Batches and concurrent queues are both supported by Action Scheduler. This is especially useful on sites with a large number of activities.

3.1 Check if the Action Scheduler package exists

If you want to check if the ActionScheduler is installed or not then you can check by this

if (class_exists('ActionScheduler') && class_exists('ActionScheduler_ListTable'))
{
echo 'Action Scheduler is already installed.';
}
else
{
echo 'You have to install Action Scheduler';
}

3.2 How to Installation Action Scheduler

Some of the popular plugins (like WooCommerce, All in One SEO, WP Mail SMTP by WPForms, WPForms Lite, etc.,) These days comes with an Action Schedule pre-installed, so in that scenario, you do not have to install it again you can simply skip this step and move to the usage step.

If you already have a composer.json file in your root folder then you can add this line "woocommerce/action-scheduler": ">=3.1.5” under “require” index so your composer will look like this

{
"require": {


"woocommerce/action-scheduler": ">=3.1.5"
},


}

If you do not have a composer.json then you can create a composer.json file and add the below code

{
"require": {
"woocommerce/action-scheduler": ">=3.1.5"
},
"config": {
"optimize-autoloader": true
}
}

After add this run below command in cli

cd /path/to/wordpress/install/dir
composer update

Now add this line at the end of the wp-config.php file

require_once( rtrim(ABSPATH,'/') . '/vendor/woocommerce/action-scheduler/action-scheduler.php' );

3.3 How to use Action Scheduler

To use schedule action you first have to instantiate it by as_schedule_recurring_action() than in the call back you have to mention your action/hook name which needs to be performed. Look into the below example for your reference.

//Hook to let scheduled action know to run your action
add_action('init', 'wh_schedule_cart_abandonment');

function wh_schedule_cart_abandonment()
{
if (false === as_next_scheduled_action('wh_schedule_cart_abandonment_action'))
{
/**
* Schedule a recurring action
*
* @param int $timestamp When the first instance of the job will run.
* @param int $interval_in_seconds How long to wait between runs.
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @param string $group The group to assign this job to or your Text Domain
*
* @return int The action ID.
*/
as_schedule_recurring_action(strtotime('now'), 10, 'wh_schedule_cart_abandonment_action', [], 'cart-abandonment');
}
}

/**
* A callback to run when the 'wh_schedule_cart_abandonment_action' scheduled action is run.
*/
function wh_check_and_send_cart_abandonment_mail()
{
# All the magic happens here
}

add_action('wh_schedule_cart_abandonment_action', 'wh_check_and_send_cart_abandonment_mail');

If you want to see the full list of API please check their official documentation actionscheduler.org

Hope you learned something new, if you do then do share this page and give a thumbs up. Also, let me know in the comment who you are using cron in your WordPress site.

Raunak Gupta

Raunak Gupta

I'm Raunak Gupta, a seasoned software developer with over 9 years of experience in a wide range of programming languages, frameworks, and tools. I started my journey as a WordPress & CakePHP developer in 2014, diving deep into the world of OOPs, Request handling, and SEO. Along the way, I crafted numerous dazzling WooCommerce stores, tamed payment gateways, optimized for full filament functionality, and achieved ultra-low latency for lightning-fast load times. My expertise extends to BI tools, website builders, DevOps, and team leadership. I like to help upcoming developers, so I share my experience through this blog and by assisting fellow developers on Stack Overflow, where I've earned a stellar reputation with over 10k+ points of recognition.

Articles: 29

4 Comments

  1. It’s nearly impossible to find knowledgeable people for this topic, however, you seem like you know what you’re talking about! Thanks

  2. That’s why I was wonderin’ why me WordPress cron wasn’t workin’ at a specific time, it was runnin’ but not at the exact given time, you know? So I ‘ad to write a custom script and add that to the crontab. I’ll give it a go on one of me sandbox servers.

Leave a Reply to El culazoCancel Reply

Your email address will not be published. Required fields are marked *