Skip to content

Instantly share code, notes, and snippets.

@andrejcremoznik
Last active December 22, 2018 23:11
Show Gist options
  • Save andrejcremoznik/7e78bd412678c08970d436cbd3fdd315 to your computer and use it in GitHub Desktop.
Save andrejcremoznik/7e78bd412678c08970d436cbd3fdd315 to your computer and use it in GitHub Desktop.
Run WordPress cron in a real cronjob

Disable WordPress built-in cron because it's unreliable and suboptimal.

  1. In wp-config.php set: define('DISABLE_WP_CRON', true);
  2. On server in $HOME create the following:
    ~/backups/         # directory to store DB backups in
    ~/bin/wp           # [WP-CLI](https://wp-cli.org/), make it executable
    ~/bin/wpbackup     # see wpbackup.sh below, make it executable
    ~/bin/wpcron10min  # see wpcron10min.sh below, make it executable
    
  3. Configure Crontab: crontab -e
    # Run every 10 minutes
    */10 * * * * $HOME/bin/wpcron10min
    # Run every 8 hours, 5 minutes past the hour
    5 */8 * * *  $HOME/bin/wpbackup
    
#!/usr/bin/env bash
# TODO: Backup directory
backup_dir="${HOME}/backups"
# TODO: List of website directories to backup
sites=(
"website1.tld"
"website2.tld"
)
backup_date=`date +'%Y-%m-%d_%H-%M'`
# Loop through $sites inside `/srv/http/*` and run `wp db export`
for site in "${sites[@]}"
do
${HOME}/bin/wp db export - --path=/srv/http/${site}/current/web/wp | gzip > ${backup_dir}/${site}_${backup_date}.sql.gz
sleep 5
done
# Remove files older than 5 days
find ${backup_dir} -type f -mtime +5 -delete
#!/usr/bin/env bash
# TODO: List of website directories to run cron on
sites=(
"website1.tld"
"website2.tld"
)
# Loop through $sites inside `/srv/http/*` and run `wp cron event run`
for site in "${sites[@]}"
do
${HOME}/bin/wp cron event run --due-now --path=/srv/http/${site}/current/web/wp > /dev/null 2>&1
sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment