<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>schedule wordpress tasks Archives - WP-CLI Mastery</title>
	<atom:link href="https://wpclimastery.com/blog/tag/schedule-wordpress-tasks/feed/" rel="self" type="application/rss+xml" />
	<link>https://wpclimastery.com/blog/tag/schedule-wordpress-tasks/</link>
	<description>Automate WordPress Like a DevOps Pro.</description>
	<lastBuildDate>Mon, 24 Nov 2025 11:16:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://wpclimastery.com/wp-content/uploads/2025/11/cropped-favicon-32x32.webp</url>
	<title>schedule wordpress tasks Archives - WP-CLI Mastery</title>
	<link>https://wpclimastery.com/blog/tag/schedule-wordpress-tasks/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Schedule WP-CLI Tasks with Cron: Complete Automation Guide</title>
		<link>https://wpclimastery.com/blog/how-to-schedule-wp-cli-tasks-with-cron-complete-automation-guide/</link>
					<comments>https://wpclimastery.com/blog/how-to-schedule-wp-cli-tasks-with-cron-complete-automation-guide/#respond</comments>
		
		<dc:creator><![CDATA[Krasen]]></dc:creator>
		<pubDate>Mon, 24 Nov 2025 11:16:24 +0000</pubDate>
				<category><![CDATA[WordPress Automation]]></category>
		<category><![CDATA[cron jobs wordpress]]></category>
		<category><![CDATA[linux cron wordpress]]></category>
		<category><![CDATA[schedule wordpress tasks]]></category>
		<category><![CDATA[wp-cli automation]]></category>
		<category><![CDATA[wp-cli cron]]></category>
		<guid isPermaLink="false">https://wpclimastery.com/?p=224</guid>

					<description><![CDATA[<p>Automating WordPress maintenance tasks saves time, reduces human error, and ensures critical operations run consistently. By combining WP-CLI with cron jobs, you can create a robust automation system that handles...</p>
<p>The post <a href="https://wpclimastery.com/blog/how-to-schedule-wp-cli-tasks-with-cron-complete-automation-guide/">How to Schedule WP-CLI Tasks with Cron: Complete Automation Guide</a> appeared first on <a href="https://wpclimastery.com">WP-CLI Mastery</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Automating WordPress maintenance tasks saves time, reduces human error, and ensures critical operations run consistently. By combining WP-CLI with cron jobs, you can create a robust automation system that handles backups, updates, cleanup, and monitoring without manual intervention.</p>



<h2 class="wp-block-heading" id="understanding-cron-and-wp-cli-integration">Understanding Cron and WP-CLI Integration</h2>



<p>Cron is a time-based job scheduler in Unix-like operating systems that executes commands at specified intervals. When paired with WP-CLI, cron enables you to automate virtually any WordPress operation, from database optimization to content publishing.</p>



<p>The combination offers powerful capabilities: scheduled backups during off-peak hours, automatic plugin updates with rollback protection, regular security scans, database cleanup operations, and automated content workflows. This automation frees developers to focus on building features rather than routine maintenance.</p>



<h2 class="wp-block-heading" id="crontab-syntax-essentials">Crontab Syntax Essentials</h2>



<p>Understanding cron syntax is fundamental to creating effective scheduled tasks. A cron expression consists of five time fields followed by the command to execute:</p>



<pre class="wp-block-code"><code>* * * * * command-to-execute
│ │ │ │ │
│ │ │ │ └─── Day of week (0-7, where 0 and 7 are Sunday)
│ │ │ └───── Month (1-12)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)
</code></pre>



<p>Common patterns include:</p>



<ul class="wp-block-list">
<li><code>0 2 * * *</code> &#8211; Daily at 2:00 AM</li>



<li><code>*/15 * * * *</code> &#8211; Every 15 minutes</li>



<li><code>0 0 * * 0</code> &#8211; Weekly on Sunday at midnight</li>



<li><code>0 3 1 * *</code> &#8211; Monthly on the 1st at 3:00 AM</li>



<li><code>0 */6 * * *</code> &#8211; Every 6 hours</li>
</ul>



<p>Special strings provide shortcuts:&nbsp;<code>@reboot</code>&nbsp;(on system startup),&nbsp;<code>@daily</code>&nbsp;(once per day),&nbsp;<code>@hourly</code>&nbsp;(once per hour),&nbsp;<code>@weekly</code>&nbsp;(once per week), and&nbsp;<code>@monthly</code>&nbsp;(once per month).</p>



<h2 class="wp-block-heading" id="setting-up-your-first-wp-cli-cron-job">Setting Up Your First WP-CLI Cron Job</h2>



<p>Begin by accessing your crontab editor with&nbsp;<code>crontab -e</code>. For a simple daily backup task:</p>



<pre class="wp-block-code"><code><em># Daily WordPress database backup at 2 AM</em>
0 2 * * * /usr/local/bin/wp --path=/var/www/html db export /backups/db-$(date +\%Y\%m\%d).sql --allow-root
</code></pre>



<p>Critical considerations when writing cron jobs: always use absolute paths for commands and files, set the correct user permissions, escape special characters (like&nbsp;<code>%</code>&nbsp;with backslash), and specify the WordPress path with the&nbsp;<code>--path</code>&nbsp;flag.</p>



<p>If WP-CLI runs as root, include the&nbsp;<code>--allow-root</code>&nbsp;flag. However, running as the web server user (like www-data) is generally safer:</p>



<pre class="wp-block-code"><code><em># Run as www-data user</em>
0 2 * * * sudo -u www-data /usr/local/bin/wp --path=/var/www/html db export /backups/db-$(date +\%Y\%m\%d).sql
</code></pre>



<h2 class="wp-block-heading" id="creating-a-maintenance-script">Creating a Maintenance Script</h2>



<p>Rather than cramming complex logic into crontab, create dedicated scripts that cron executes. This approach improves maintainability, enables version control, and facilitates testing.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># /opt/scripts/wp-maintenance.sh</em>
<em># WordPress daily maintenance automation</em>

set -euo pipefail

WP_PATH="/var/www/html"
BACKUP_DIR="/backups/wordpress"
LOG_FILE="/var/log/wp-maintenance.log"
DATE=$(date +%Y%m%d-%H%M%S)

<em># Logging function</em>
log() {
    echo "&#91;$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "Starting WordPress maintenance"

<em># Create backup directory if it doesn't exist</em>
mkdir -p "$BACKUP_DIR"

<em># Database backup</em>
log "Creating database backup"
wp --path="$WP_PATH" db export "$BACKUP_DIR/database-$DATE.sql" || {
    log "ERROR: Database backup failed"
    exit 1
}

<em># Optimize database</em>
log "Optimizing database"
wp --path="$WP_PATH" db optimize

<em># Clean up old backups (keep last 7 days)</em>
log "Cleaning old backups"
find "$BACKUP_DIR" -name "database-*.sql" -mtime +7 -delete

<em># Update plugins (excluding specific ones)</em>
log "Updating plugins"
wp --path="$WP_PATH" plugin update --all --exclude=woocommerce,elementor

<em># Clear transients</em>
log "Clearing expired transients"
wp --path="$WP_PATH" transient delete --expired

<em># Generate thumbnail for recent uploads</em>
log "Regenerating recent thumbnails"
wp --path="$WP_PATH" media regenerate --yes --only-missing

<em># Clear object cache if available</em>
if wp --path="$WP_PATH" cache flush &amp;&gt;/dev/null; then
    log "Cache flushed successfully"
fi

log "Maintenance completed successfully"
</code></pre>



<p>Make the script executable and add to crontab:</p>



<pre class="wp-block-code"><code>chmod +x /opt/scripts/wp-maintenance.sh

<em># In crontab</em>
0 3 * * * /opt/scripts/wp-maintenance.sh
</code></pre>



<h2 class="wp-block-heading" id="advanced-scheduling-strategies">Advanced Scheduling Strategies</h2>



<p>Complex WordPress operations often require conditional logic, environment-specific configurations, and coordination between multiple tasks.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># Advanced scheduling with environment detection</em>

WP_PATH="/var/www/html"

<em># Detect environment</em>
ENVIRONMENT=$(wp --path="$WP_PATH" config get WP_ENVIRONMENT_TYPE)

case $ENVIRONMENT in
    production)
        <em># Conservative updates in production</em>
        wp --path="$WP_PATH" plugin update --minor
        wp --path="$WP_PATH" core update --minor
        ;;
    staging)
        <em># More aggressive updates in staging</em>
        wp --path="$WP_PATH" plugin update --all
        wp --path="$WP_PATH" core update
        wp --path="$WP_PATH" theme update --all
        ;;
    development)
        <em># Full updates including development versions</em>
        wp --path="$WP_PATH" plugin update --all
        wp --path="$WP_PATH" core update --version=nightly
        ;;
esac
</code></pre>



<p>For coordinated tasks across multiple sites:</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># Multi-site update coordination</em>

SITES=(
    "/var/www/site1"
    "/var/www/site2"
    "/var/www/site3"
)

for site in "${SITES&#91;@]}"; do
    echo "Processing: $site"

    <em># Check if site is healthy before updating</em>
    if wp --path="$site" core is-installed; then
        wp --path="$site" core update --minor
        wp --path="$site" plugin update --all --exclude=custom-plugin

        <em># Verify site is still functional</em>
        if ! wp --path="$site" core verify-checksums; then
            echo "WARNING: Checksum verification failed for $site"
            <em># Send alert notification</em>
        fi
    else
        echo "ERROR: WordPress not properly installed at $site"
    fi
done
</code></pre>



<h2 class="wp-block-heading" id="error-handling-and-notifications">Error Handling and Notifications</h2>



<p>Production cron jobs require robust error handling and notification systems to alert administrators when problems occur.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># wp-backup-with-notifications.sh</em>

set -euo pipefail

ADMIN_EMAIL="admin@example.com"
WP_PATH="/var/www/html"
BACKUP_DIR="/backups"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

send_alert() {
    local subject="$1"
    local message="$2"
    echo "$message" | mail -s "$subject" "$ADMIN_EMAIL"
}

<em># Trap errors</em>
trap 'send_alert "WordPress Backup Failed" "Backup script failed at line $LINENO"' ERR

<em># Check disk space</em>
AVAILABLE_SPACE=$(df "$BACKUP_DIR" | tail -1 | awk '{print $4}')
if &#91; "$AVAILABLE_SPACE" -lt 1048576 ]; then  <em># Less than 1GB</em>
    send_alert "Low Disk Space Warning" "Available space: ${AVAILABLE_SPACE}KB"
    exit 1
fi

<em># Perform backup</em>
wp --path="$WP_PATH" db export "$BACKUP_DIR/db-$TIMESTAMP.sql"

<em># Backup files</em>
tar -czf "$BACKUP_DIR/files-$TIMESTAMP.tar.gz" -C "$WP_PATH" wp-content/uploads

<em># Verify backup integrity</em>
if &#91; -f "$BACKUP_DIR/db-$TIMESTAMP.sql" ] &amp;&amp; &#91; -f "$BACKUP_DIR/files-$TIMESTAMP.tar.gz" ]; then
    BACKUP_SIZE=$(du -sh "$BACKUP_DIR" | cut -f1)
    send_alert "Backup Completed Successfully" "Backup size: $BACKUP_SIZE"
else
    send_alert "Backup Verification Failed" "One or more backup files are missing"
    exit 1
fi
</code></pre>



<h2 class="wp-block-heading" id="logging-and-monitoring">Logging and Monitoring</h2>



<p>Comprehensive logging helps troubleshoot issues and track automation performance over time.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># Enhanced logging example</em>

LOG_DIR="/var/log/wp-automation"
mkdir -p "$LOG_DIR"

<em># Create dated log file</em>
LOG_FILE="$LOG_DIR/maintenance-$(date +%Y%m%d).log"

<em># Logging function with levels</em>
log() {
    local level=$1
    shift
    local message="$@"
    echo "&#91;$(date '+%Y-%m-%d %H:%M:%S')] &#91;$level] $message" &gt;&gt; "$LOG_FILE"
}

<em># Execute WP-CLI command with logging</em>
wp_execute() {
    local cmd="$@"
    log "INFO" "Executing: wp $cmd"

    if output=$(wp $cmd 2&gt;&amp;1); then
        log "SUCCESS" "Command completed: $output"
        return 0
    else
        log "ERROR" "Command failed: $output"
        return 1
    fi
}

<em># Usage</em>
wp_execute --path=/var/www/html plugin list --status=active
wp_execute --path=/var/www/html core update --minor
</code></pre>



<p>Monitor log files with automated analysis:</p>



<pre class="wp-block-code"><code><em># Cron job to analyze logs and send daily summary</em>
0 8 * * * /opt/scripts/analyze-logs.sh

<em># analyze-logs.sh</em>
<em>#!/bin/bash</em>
LOG_DIR="/var/log/wp-automation"
YESTERDAY=$(date -d "yesterday" +%Y%m%d)
LOG_FILE="$LOG_DIR/maintenance-$YESTERDAY.log"

if &#91; -f "$LOG_FILE" ]; then
    ERRORS=$(grep -c "\&#91;ERROR\]" "$LOG_FILE" || true)
    SUCCESSES=$(grep -c "\&#91;SUCCESS\]" "$LOG_FILE" || true)

    mail -s "WP Automation Summary $YESTERDAY" admin@example.com &lt;&lt;EOF
Daily WordPress Automation Summary

Successful operations: $SUCCESSES
Failed operations: $ERRORS

Recent errors:
$(grep "\&#91;ERROR\]" "$LOG_FILE" | tail -5)
EOF
fi
</code></pre>



<h2 class="wp-block-heading" id="security-considerations">Security Considerations</h2>



<p>Secure your cron jobs by limiting file permissions, using dedicated service accounts, and protecting sensitive information.</p>



<pre class="wp-block-code"><code><em># Create dedicated user for WordPress automation</em>
sudo useradd -r -s /bin/bash wpautomation

<em># Set appropriate permissions</em>
chmod 700 /opt/scripts/wp-maintenance.sh
chown wpautomation:wpautomation /opt/scripts/wp-maintenance.sh

<em># Store credentials securely</em>
cat &gt; /home/wpautomation/.wp-cli-credentials &lt;&lt; EOF
SMTP_PASSWORD=secure_password
API_KEY=secret_key
EOF

chmod 600 /home/wpautomation/.wp-cli-credentials
chown wpautomation:wpautomation /home/wpautomation/.wp-cli-credentials

<em># Crontab for wpautomation user</em>
sudo -u wpautomation crontab -e
</code></pre>



<h2 class="wp-block-heading" id="testing-cron-jobs">Testing Cron Jobs</h2>



<p>Before deploying to production, test your cron jobs thoroughly:</p>



<pre class="wp-block-code"><code><em># Run manually to verify behavior</em>
/opt/scripts/wp-maintenance.sh

<em># Test with verbose WP-CLI output</em>
wp --path=/var/www/html plugin update --all --dry-run --debug

<em># Verify cron syntax</em>
<em># Install cron expression parser</em>
npm install -g cron-validate

<em># Check if your cron expression is valid</em>
echo "0 3 * * *" | cron-validate
</code></pre>



<p>Use temporary increased frequency for testing:</p>



<pre class="wp-block-code"><code><em># Test frequency (every 5 minutes)</em>
*/5 * * * * /opt/scripts/test-automation.sh

<em># Production frequency (daily at 3 AM)</em>
<em># 0 3 * * * /opt/scripts/wp-maintenance.sh</em>
</code></pre>



<h2 class="wp-block-heading" id="best-practices-summary">Best Practices Summary</h2>



<p>Always redirect output appropriately &#8211; either to log files or use&nbsp;<code>&gt;/dev/null 2&gt;&amp;1</code>&nbsp;to suppress. Include timeout mechanisms for long-running operations to prevent hanging processes. Implement file locking to prevent concurrent execution when scripts shouldn&#8217;t overlap.</p>



<p>Use environment variables for configuration rather than hardcoding values. Document each cron job with comments explaining its purpose and frequency. Regularly review and audit scheduled tasks to remove obsolete jobs.</p>



<p>Consider using cron management tools like&nbsp;<code>whenever</code>&nbsp;(Ruby) or&nbsp;<code>cronitor</code>&nbsp;for monitoring. Set up health checks to verify cron jobs are executing as expected.</p>



<h2 class="wp-block-heading" id="related-links">Related Links</h2>



<ul class="wp-block-list">
<li><a href="https://developer.wordpress.org/cli/commands/">WP-CLI Commands Reference</a></li>



<li><a href="https://crontab.guru/">Crontab Guru &#8211; Cron Schedule Expression Editor</a></li>



<li><a href="https://www.man7.org/linux/man-pages/man5/crontab.5.html">Linux Cron Tutorial</a></li>



<li><a href="https://wordpress.org/support/article/wordpress-backups/">WordPress Maintenance Best Practices</a></li>



<li><a href="https://developer.wordpress.org/advanced-administration/">Automated WordPress Deployment Guide</a></li>
</ul>
<p>The post <a href="https://wpclimastery.com/blog/how-to-schedule-wp-cli-tasks-with-cron-complete-automation-guide/">How to Schedule WP-CLI Tasks with Cron: Complete Automation Guide</a> appeared first on <a href="https://wpclimastery.com">WP-CLI Mastery</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://wpclimastery.com/blog/how-to-schedule-wp-cli-tasks-with-cron-complete-automation-guide/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
