Run scheduled jobs on a real clock, not on visitor traffic
One of my side projects is a WordPress site on shared hosting. One afternoon the whole server
got slow. Every PHP request stalled, and when I looked at the slowest hits reaching the origin,
a big share of them were not pages at all. They were hundreds of requests to wp-cron.php,
the file WordPress uses to run its scheduled tasks.
Nobody was calling that file on purpose. That is how the default scheduler works.
How a traffic-driven scheduler works
WordPress has no clock of its own. On a normal page view it checks whether any scheduled task is due, and if one is, it fires off a background HTTP request to itself to run it. No visitors means no scheduled work. Lots of visitors means lots of checks, and a steady stream of extra requests to the cron endpoint.
That is a reasonable default for a site that might live on a host with no cron access at all. It is a bad fit for a busy site on a server you share with other people, for two reasons:
- Load shows up when you can least afford it. The extra requests scale with traffic, so a spike in visitors is also a spike in scheduler requests. When the server is already overloaded, each of those requests waits in the same queue as your real pages.
- Timing depends on visitors. A task scheduled for 3 AM runs whenever the first person shows up after 3 AM. On a quiet night that could be hours late.
The fix is old and boring: turn off the traffic trigger and let the operating system’s cron run the due tasks on a fixed tick.
The approach
There are two pieces, and both have to be right.
- Set
DISABLE_WP_CRONtotruein the site config, so page views stop spawning scheduler requests. - Add one crontab line that runs every five minutes and asks WP-CLI to run whatever is due.
The interesting part was not the idea. It was making the setup safe to run from a deploy pipeline over and over, because I did not want a one-off change I made by hand on a server and then forgot about.
Install the cron line idempotently
The naive version appends a line to the crontab. Run your deploy ten times and you have ten copies of the job, all fighting each other. So the line carries a tag in a trailing comment, and the installer always removes any line with that tag before writing the new one:
MARK='# site-scheduler'
line="*/5 * * * * cd $WEB_ROOT && flock -n $HOME/.scheduler.lock wp cron event run --due-now > $HOME/.scheduler.last 2>&1 $MARK"
existing=$(crontab -l 2>/dev/null || true)
others=$(printf '%s\n' "$existing" | grep -v -F "$MARK" | sed '/^[[:space:]]*$/d')
if [ -n "$others" ]; then
printf '%s\n%s\n' "$others" "$line" | crontab -
else
printf '%s\n' "$line" | crontab -
fi
A few details in there earn their place:
- Every other line is kept. The shared account may have crontab entries I did not write. The script only owns the tagged line and leaves the rest exactly as it found them.
flock -nprevents overlap. If one run is still going when the next tick arrives, the new one simply exits. Without it, a slow run on a busy server could stack up copies.- The output goes to one file that gets overwritten. I can see what the last run did, and the log can never grow until it fills the disk.
Change the config carefully
Editing a live config file from a script is the part that can take the whole site down, so I treat it like surgery. Check first, back up, change, verify, and restore if anything looks off:
current=$(wp config get DISABLE_WP_CRON 2>/dev/null || true)
if [ "$current" != "1" ] && [ "$current" != "true" ]; then
cfg=$(wp config path)
backup="$cfg.bak-$(date +%Y%m%d%H%M%S)"
cp -p "$cfg" "$backup"
if wp config set DISABLE_WP_CRON true --raw --type=constant \
&& php -l "$cfg" >/dev/null; then
echo "scheduler trigger disabled (backup: $backup)"
else
cp -p "$backup" "$cfg"
echo "config change failed, restored from $backup"
exit 1
fi
fi
The syntax check after the edit matters. A config file that does not parse means every page returns an error, and I would rather the deploy step fail loudly than ship that.
Run it from the pipeline, and give it a dry run
The script runs as the last step of every deploy, so the server always converges to the same state no matter what happened to it in between. I also added a manual workflow with a “verify only” switch that changes nothing and just prints the current state: the config value, the tagged crontab line, the output of the last run, and the list of upcoming events. That is the first thing I reach for when someone asks whether the scheduler is actually running.
Test the installer, not just the site
A shell script that edits a crontab is easy to get almost right. So there is a small test that
puts fake wp, crontab, and php commands on the PATH, seeds a crontab with a couple of
unrelated lines, and then runs the installer three times. It asserts:
- exactly one tagged line exists afterward,
- the unrelated lines are all still there,
- the config constant was set once,
- and verify-only mode changes nothing at all.
Running it three times is the whole point. Idempotence bugs only show up on the second run.
Tradeoffs
- Tasks can lag by up to the tick. Anything that used to fire a few seconds after an event, like a social post or a search engine ping, now waits for the next five minute tick. For my site that is fine. If you need tighter timing, shorten the interval or move that job somewhere else.
- You now own a crontab entry. If the host migrates your account or you move servers, the line has to come with you. Running the installer on every deploy is how I keep that honest.
- Check what still depends on the old trigger. Before flipping the switch, I went through every scheduled job and noted which ones ran through the built-in scheduler and which were already triggered from outside. An old endpoint that called the scheduler on demand became a no-op, and I wrote that down rather than letting it surprise me later.
- Rollback should be two commands. Set the constant back to false and filter the tagged line out of the crontab. I put both in the README next to the script.
The pattern
If your scheduler only ticks when a user shows up, it is borrowing your users’ requests to do your background work. That is fine until the server is struggling, and then it makes things worse. Give scheduled work a real clock, make the setup something your deploy can run a hundred times without side effects, and test it by running it more than once.