Setup External Cron Jobs using Cron Triggers – Cloudflare Workers

Clock Hand

Cron Jobs are usually a culprit in some WordPress sites for speed. If you haven’t disabled inbuilt cron jobs, every time a user visits your page, or you open admin area, cron jobs might be exected.

I’ve written more about what are cron jobs, how WordPress uses cron jobs, how to disable inbuilt cron jobs etc in the below blog post. If you haven’t read it, pls read it before going through this tutorial:

This tutorial is for setting up external Cron Jobs using Cloudflare Worker’s new Cron Triggers.

What is Cron Trigger and Service Worker in Cloudflare?

Service Worker – A custom script that can be deployed to their edge network (all PoPs). We can write whatever functionality in there. Code is executed in their edge servers.

Cron Trigger – In UNIX systems (like Linux), ‘crontab’ is a list of commands that you want to run on a regular schedule. Cron Trigger in Cloudflare allows us to execute a service worker on a schedule.

Pricing of Cron Trigger & Service Workers

There is no additional cost for Cron Trigger.

Every time a cron trigger happens, a service worker script is executed. Service Workers comes with a free tier of 10k requests per day.

Let’s say you run a cron job every 10 mins; it only counts 144 requests a day (60/10*24). So, it’s free!

How to Setup Cron Trigger for WordPress Cron Jobs

Goto your account Cloudflare Dashboard -> Workers

Click ‘Create a Worker’ and paste the below script:

addEventListener("scheduled", event => {
  event.waitUntil(handleScheduled(event))
})

async function handleScheduled(event) {
  await fetch("https://example.com/wp-cron.php?doing_wp_cron")
}

NOTE: Replace “example.com” with your domain name.

Click ‘Save and deploy’.

Now, go back and go to the ‘Triggers’ tab and click ‘Add Cron Trigger’.

By default, it will be ‘Every 30 minutes’. I’ve configured it to every 10 minutes.

Click ‘Save’, and you’re done!

Video Tutorial

WordPress External Jobs using Cron Triggers from Cloudflare Workers

Disable WordPress inbuilt Cron Job

Make sure to disable inbuilt Cron Job in your WordPress. Otherwise, there is no point of configuring external cron jobs!

Add the following line to wp-config.php file

define('DISABLE_WP_CRON', true);

Comments are closed.

You May Also Like