THE GOAL

Create a system cron for WordPress, that is accessible and can be easily tweaked to provide more details. Here some basic information about crons and the tools I am going to use …

WordPress CRON

In WordPress, the term “cron” refers to the system used for scheduling tasks to be executed at predefined intervals. The WordPress cron system allows various actions to be scheduled, such as publishing scheduled posts, checking for updates, sending email notifications, and running other scheduled tasks.

WordPress includes its own pseudo-cron system, which relies on visitors accessing your site. When a visitor loads a page on your WordPress site, WordPress checks if there are any scheduled tasks that need to be executed. If there are, it runs those tasks. This system works well for most sites, but it has limitations, particularly for low-traffic sites or sites that need precise scheduling.

To overcome these limitations, WordPress also provides the option to use a real cron system. With a real cron system, tasks are scheduled and executed independently of visitor traffic. This can be more reliable and precise than relying on visitors to trigger cron tasks.

To set up a real cron system for WordPress, you typically need to configure your server’s cron job scheduler to trigger the wp-cron.php file at regular intervals. This file handles the execution of scheduled WordPress tasks.

List scheduled WordPress events

WP Crontrol is a solid UI, to list and see whats happening in the background.

  • View all cron events along with their arguments, recurrence, callback functions, and when they are next due.
  • Edit, delete, pause, resume, and immediately run cron events.
  • Add new cron events.
  • Bulk delete cron events.
  • Add and remove custom cron schedules.
  • Export and download cron event lists as a CSV file.

WP-CLI

WP-CLI (WordPress Command Line Interface) is a powerful command-line tool that allows developers and administrators to interact with WordPress websites directly through the command line, without needing to use a web browser.

It provides a wide range of commands for managing various aspects of a WordPress site, such as executing crons / scheduled tasks, installing plugins, updating themes, managing users, and much more.

Most WordPress hosts have it preinstalled. Installation

Test CRON

  1. # Test WP Cron spawning system
  2. $ wp cron test
  3. Success: WP-Cron spawning is working as expected.

Run CRON

  1. # Schedule a new cron event
  2. $ wp cron event schedule cron_test
  3. Success: Scheduled event with hook 'cron_test' for 2024-01-31 10:19:16 GMT.
  4.  
  5. # Run all cron events due right now
  6. $ wp cron event run --due-now
  7. Success: Executed a total of 2 cron events.
  8.  
  9. # Delete all scheduled cron events for the given hook
  10. $ wp cron event delete cron_test
  11. Success: Deleted 2 instances of the cron event 'cron_test'.
  12.  
  13. # List scheduled cron events in JSON
  14. $ wp cron event list --fields=hook,next_run --format=json
  15. [{"hook":"wp_version_check","next_run":"2024-01-31 10:15:13"},{"hook":"wp_update_plugins","next_run":"2016-05-31 10:15:13"},{"hook":"wp_update_themes","next_run":"2016-05-31 10:15:14"}]

ntfy.sh

ntfy (pronounced notify) is a simple HTTP-based pub-sub notification service. It allows you to send notifications to your phone or desktop via scripts from any computer, and/or using a REST API.

You can host your own docker instance or use the hosted solution.

The documentation is detailed and offers many ways to tweak the resulting notification.

Server CRON / THE OLD WAY

  1. /** Disable virtual cron in wp-config.php */
  2. define('DISABLE_WP_CRON', true);
  1. 0 13 * * * wget -q -O - https://domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
  2.  

Server – CRON / THE NEW COMBINED WAY

I am not showing you how to create a system cron, that can vary depending on your hosting provider. Some of you will just setup / modify the crontab themselves. So here an example of how I use it these days …

  1. */30 * * * * OUTPUT=$(/bin/bash -c "/path/to/wp-cli/wp --path=/path/to/wp/install/ cron event run --url=https://your-website.com/if/multisite/ --due-now" 2>&1) && curl -u %ntfy_token% -H "Filename:your_cron_output.txt" -H "Title:Your Cron" -d "$OUTPUT" "https://ntfy.server.com/topic"

Lets dissect this :)

Execution Timeframe – Minute / Hour / Day (month) / Month / Day (week)

See example usage on crontab.guru.

  1. */30 * * * *

Capture the output

Im using a variable to capture the output, allowing me to pass it to ntfy.

  1. OUTPUT=$()

The command part 1

Use bash to launch wp-cli, passing in required parameters to make sure the right website is targeted.
I am using –due-now to only launch those schedules that are actually pending. >/dev/null 2>&1 prevents any emails to be send for this cron job, it redirects the error stream into the output stream. Always helpful to remove it for the first testdrive.

>/dev/null: redirects standard output (stdout) to /dev/null
2>&1: redirects standard error (2) to standard output (1), which then discards it as well since standard output has already been redirected :)

  1. /bin/bash -c "/path/to/wp-cli/wp --path=/path/to/wp/install/ cron event run --url=https://your-website.com/if/multisite/ --due-now" >/dev/null 2>&1

The command part 2

This part sends the output to a ntfy instance / topic.

  1. curl -u %ntfy_token%
  2.      -H "Filename:your_cron_output.txt"
  3.      -H "Title:Your Cron"
  4.      -d "$OUTPUT"
  5.      "https://ntfy.server.com/topic"
  1. -u %token% login / auth with your token
  2. -H “Filename: …” this will move the body text into an attachment file. You can remove this and all output will be part of the body text. ntfy has a body message length limit and will shift to an attachment when reached.
  3. -H “Title: …” Title for the message
  4. -d “$Output” Set the body message to the output we captured, using the set variable
  5. Finally the url to post to, the ntfy instance and topic.

You can set many other things as well, like tags, images …. Check the documentation about publishing for more options. You can even redirect to an email account ;)

Detecting WP-CLI execution programmatically

  1. if ( defined( 'WP_CLI' ) && WP_CLI ) {
  2.     // Do WP-CLI specific things.
  3. }

Detecting WP-CRON execution programmatically

  1. if ( defined( 'DOING_CRON' ) )
  2. {
  3.     // Do something
  4. }

Enjoy coding …
Alex

Alex

I am a full-stack developer. I love programming,  design and know my way around server architecture as well.  I would never feel complete, with one of these missing. I have a broad range of interests, that’s why I constantly dive into new technologies and expand my knowledge where ever required. Technologies are evolving fast and I enjoy using the latest. Apart from that, I am a peace loving guy who tries to have people around him that think the same.  I truly believe in the principle: “If you help someone, someone will help you, when you need it."

Published by
Alex

Recent Posts

B&B / Hotel Booking Solutions for WordPress | 2024

BOOKING SOLUTIONS 202x This is my take on a subset of booking, appointment, PMS or… Read More

4 weeks ago

2024 is here and now :)

2024, what's cooking? Slowly getting into the 2024 spirit. 3 projects coming to a close… Read More

4 months ago

2023 ends and whats next !

Short look back at 2023 This has been a busy and interesting year. I am… Read More

4 months ago

cubicFUSION Grid Tweaker – Elementor Grid made easy.

Elementor Pro provides grid containers as an experimental feature. The options provided are limited, when… Read More

5 months ago

Archaeology Travel Booth – Travel Innovation Summit 2023

Archaeology Travel is an online travel guide for people who enjoy exploring the world’s pasts.… Read More

6 months ago

Artificial intelligence (AI) is revolutionizing the way we interact with images

Artificial intelligence (AI) has revolutionized the way we interact with images, and the current AI… Read More

6 months ago