Schedule Weekly Sunday Maintenance at 3 AM | CronBase
0 3 * * 0 Every Sunday morning at three o'clock
This cron expression schedules a task to run every Sunday morning at exactly 3:00 AM. It is a highly popular cadence for executing heavy weekly maintenance, database optimization, disk defragmentation, log rotation, and deep analytical reports during off-peak hours when user traffic and system load are at their absolute lowest.
- Minute
- 0
- Hour
- 3
- Day of Month
- *
- Month
- *
- Day of Week
- 0
Next 5 Runs
- in 6h 34m
- in 7d 6h
- in 14d 6h
- in 21d 6h
- in 28d 6h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Ensure the script exits on any error
set -euo pipefail
# Log file configuration
LOG_FILE="/var/log/weekly_maintenance.log"
# Main execution function
run_maintenance() {
echo "[$(date -u)] Starting weekly maintenance task..." >> "$LOG_FILE"
# Add your production backup or cleanup command here
# e.g., pg_dumpall -U postgres | gzip > /backups/db_$(date +%F).sql.gz
echo "[$(date -u)] Maintenance completed successfully." >> "$LOG_FILE"
}
# Execute with error logging
if ! run_maintenance; then
echo "[$(date -u)] CRITICAL: Weekly maintenance failed!" >&2
exit 1
fi › Setup notes
Add the script to your system cron by running 'crontab -e' and adding the line: '0 3 * * 0 /path/to/your/script.sh'. Ensure the script has executable permissions using 'chmod +x'.
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule task to run every Sunday at 3:00 AM
cron.schedule('0 3 * * 0', () => {
console.log(`[${new Date().toISOString()}] Initiating weekly cleanup job...`);
exec('/usr/local/bin/weekly-cleanup.sh', (error, stdout, stderr) => {
if (error) {
console.error(`[ERROR] Weekly cleanup failed: ${error.message}`);
return;
}
if (stderr) {
console.warn(`[WARNING] Standard error output: ${stderr}`);
}
console.log(`[SUCCESS] Cleanup output:\n${stdout}`);
});
}, {
scheduled: true,
timezone: "UTC"
}); › Setup notes
Install 'node-cron' via npm. Run this process in the background using a process manager like PM2 to guarantee continuous execution and automatic restarts.
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def execute_weekly_maintenance():
logger.info("Starting weekly database vacuum and optimization...")
try:
# Simulate maintenance work
# db.vacuum_analyze_all()
logger.info("Weekly maintenance completed successfully.")
except Exception as e:
logger.error(f"Maintenance failed: {str(e)}", exc_info=True)
if __name__ == '__main__':
scheduler = BlockingScheduler(timezone="UTC")
# 0 3 * * 0 translates to: minute 0, hour 3, day of week 6 (Sunday in APScheduler standard is 6 or 'sun')
scheduler.add_job(execute_weekly_maintenance, 'cron', day_of_week='sun', hour=3, minute=0)
logger.info("Scheduler started. Waiting for Sunday 3:00 AM UTC...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass › Setup notes
Install APScheduler via pip: 'pip install apscheduler'. Run the script inside a systemd service to ensure it starts on boot and runs continuously.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
// Use UTC timezone to avoid DST issues
nyc, err := time.LoadLocation("UTC")
if err != nil {
log.Fatalf("Failed to load timezone: %v", err)
}
c := cron.New(cron.WithLocation(nyc))
// Register the job to run at 3:00 AM on Sunday
_, err = c.AddFunc("0 3 * * 0", func() {
log.Println("Weekly maintenance job started...")
// Perform production safety checks and database rotations here
log.Println("Weekly maintenance job finished successfully.")
})
if err != nil {
log.Fatalf("Error scheduling cron job: %v", err)
}
c.Start()
log.Println("Cron engine initialized. Scheduled for every Sunday at 03:00 UTC.")
// Keep application running until interrupted
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
c.Stop()
} › Setup notes
Initialize a Go module, run 'go get github.com/robfig/cron/v3', and execute the compiled binary inside your production environment.
package com.example.cron;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class WeeklyMaintenanceScheduler {
private static final Logger logger = LoggerFactory.getLogger(WeeklyMaintenanceScheduler.class);
// Spring's cron syntax uses 6 fields: second, minute, hour, day, month, day-of-week.
// "0 0 3 * * SUN" targets 3:00:00 AM every Sunday.
@Scheduled(cron = "0 0 3 * * SUN", zone = "UTC")
public void runWeeklyMaintenance() {
logger.info("Initializing scheduled Sunday maintenance tasks...");
try {
// Invoke service layer task
logger.info("Scheduled Sunday maintenance executed successfully.");
} catch (Exception e) {
logger.error("Critical failure during weekly maintenance execution: ", e);
}
}
} › Setup notes
Ensure '@EnableScheduling' is added to your main Spring Boot Application configuration class to activate scheduled tasks.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekly-maintenance-job
namespace: default
spec:
schedule: "0 3 * * 0"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 1800
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: worker
image: alpine:latest
command:
- /bin/sh
- -c
- "echo 'Starting weekly database maintenance'; /usr/local/bin/backup-script.sh"
restartPolicy: OnFailure › Setup notes
Save the manifest as 'weekly-cronjob.yaml' and apply it using 'kubectl apply -f weekly-cronjob.yaml'. Monitor executions with 'kubectl get cronjob weekly-maintenance-job'.
Last verified:
Keep this cron job monitored 24/7
UptimeRobot alerts you the moment a scheduled job stops responding. Free plan monitors up to 50 endpoints — no credit card required.
Platform Equivalents
AWS EventBridge
Standard cron expressions often need conversion for AWS EventBridge schedules.
cron(0 3 ? * 0 *) Systemd Timer
OnCalendarSun *-*-* 03:00:00
[Unit]
Description=Timer for cron expression: 0 3 * * 0
[Timer]
OnCalendar=Sun *-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How does Daylight Saving Time affect a job scheduled at 3 AM on Sunday?
Depending on your local timezone rules, the 3:00 AM transition during Spring Forward might cause the cron daemon to skip execution or run it late, while Autumn Back could trigger it twice if the daemon doesn't handle offsets correctly. Running your system clock in UTC entirely eliminates this unpredictability.
Can I run multiple heavy maintenance scripts simultaneously at this hour?
It is highly discouraged to run multiple resource-intensive tasks at exactly 3:00 AM. Instead, chain your scripts sequentially using a wrapper script or orchestrator, or space them out (e.g., one at 3:00 AM, another at 4:30 AM) to prevent CPU starvation and disk I/O bottlenecks.
What happens if the server is offline when 3:00 AM Sunday passes?
Standard cron daemons will not run missed jobs once the server boots back up. If missed executions are unacceptable for your workflow, you should utilize anacron (for non-server systems) or a modern orchestration tool like Kubernetes CronJobs with a concurrency policy and starting deadline.
Is Sunday at 0 or 7 in standard cron configurations?
In standard POSIX and Vixie cron implementations, both 0 and 7 represent Sunday. Using 0 is universally supported across almost all cron engines, making it the safest choice for cross-platform compatibility and Infrastructure-as-Code definitions.
How should I handle alerting for a job that only runs once a week?
Passive monitoring (waiting for a failure alert) is risky for weekly jobs because a silent failure might go unnoticed for days. Implement 'dead man's snitch' heartbeat monitoring, where your job pings an external monitoring service upon successful completion, alerting you if no ping is received by 3:15 AM Sunday.
* Explore
Related expressions you might need
Last verified: