Skip to content

Instantly share code, notes, and snippets.

@rkok
Created July 24, 2024 05:34
Show Gist options
  • Save rkok/46a4592523da437d96622d943e674263 to your computer and use it in GitHub Desktop.
Save rkok/46a4592523da437d96622d943e674263 to your computer and use it in GitHub Desktop.
Plesk wp-cron staggered scheduler
#!/usr/bin/env bash
#####################
# Buggy, but good enough.
# Walks over users' Plesk-managed wp-cron entries, to change this:
# <whatever> * * * * /opt/plesk/php/8.2/bin/php -f 'httpdocs/wp-cron.php'
# ...into something like this:
# 7,23,39,55 /opt/plesk/php/8.2/bin/php -f 'httpdocs/wp-cron.php'
# so that wp-cron runs are spread out as much as possible,
# to reduce simultaneous memory usage.
#####################
i=1
WEBUSERS="$(grep -lE '^[^#].*plesk.*wp-cron.php' /var/spool/cron/* | cut -d/ -f5)"
NUSERS="$(echo "$WEBUSERS" | wc -l)"
echo "Dividing wp-cron jobs into a staggered schedule..."
for WEBUSER in $WEBUSERS; do
MINS=
for j in {0..59}; do
if [ $((j % NUSERS)) == $((i % 60 % NUSERS)) ]; then
MINS="$MINS $j"
fi
done
NEWSCHED="$(echo $MINS | tr ' ' ',') * * * *"
echo -ne "$WEBUSER:\t"
( crontab -l -u "$WEBUSER" \
| perl -pe 's/^(?<!#)(?:[\w*][ \t]+){5}(.+plesk.+wp-cron.php.+)$/'"$NEWSCHED"' $1/' \
| tee /proc/self/fd/3 \
| crontab -u "$WEBUSER" - ;
) 3>&1 | grep wp-cron
i=$((i+1))
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment