Run Weekly Maintenance Tasks on Sunday | CronBase
0 8 * * 0 Every Sunday morning at eight AM.
The `0 8 * * 0` cron expression schedules a task to execute every Sunday at exactly 8:00 AM. This weekly cadence is ideal for running low-traffic database backups, generating weekly performance reports, executing system updates, and conducting routine maintenance tasks without impacting standard weekday business operations.
- Minute
- 0
- Hour
- 8
- Day of Month
- *
- Month
- *
- Day of Week
- 0
Next 5 Runs
- in 11h 34m
- in 7d 11h
- in 14d 11h
- in 21d 11h
- in 28d 11h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Production Bash script for Sunday 8 AM Cron Job
# Usage: Add to crontab via: 0 8 * * 0 /path/to/script.sh >> /var/log/weekly_job.log 2>&1
set -euo pipefail
LOCKFILE="/var/run/weekly_maintenance.lock"
exec 200>"$LOCKFILE"
if ! flock -n 200; then
echo "[$(date -u)] Error: Another instance of the weekly maintenance job is already running." >&2
exit 1
fi
echo "[$(date -u)] Starting weekly maintenance tasks..."
# Add production tasks here (e.g., system cleanup, backup validation)
# Example: tar -czf /backups/weekly_$(date +%F).tar.gz /data
echo "[$(date -u)] Weekly maintenance completed successfully." › Setup notes
Save the script to your server, make it executable using 'chmod +x script.sh', and add it to your system crontab using 'crontab -e'.
// Node.js weekly cron implementation using 'node-cron'
// Run: npm install node-cron
const cron = require('node-cron');
const schedule = '0 8 * * 0'; // Sunday at 8:00 AM
console.log(`Initializing weekly cron worker on schedule: ${schedule}`);
cron.schedule(schedule, async () => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] Weekly execution started.`);
try {
// Simulate production task (e.g., database cleanup or cache eviction)
await performWeeklyCleanup();
console.log(`[${timestamp}] Weekly execution completed successfully.`);
} catch (error) {
console.error(`[${timestamp}] Critical error during weekly execution:`, error);
// In production, integrate with PagerDuty, Sentry, or Slack webhooks here
}
}, {
scheduled: true,
timezone: "UTC" // Enforcing UTC prevents Daylight Saving Time shift issues
});
async function performWeeklyCleanup() {
return Promise.resolve();
} › Setup notes
Install the required 'node-cron' package, save the file as 'scheduler.js', and run it using 'node scheduler.js' inside a process manager like PM2.
# Python weekly cron task using 'apscheduler'
# Run: pip install apscheduler
import logging
import sys
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
def execute_weekly_job():
logging.info("Starting scheduled weekly maintenance job.")
try:
# Real-world logic: Database optimization, index rebuilding, or log rotation
logging.info("Weekly task finished successfully.")
except Exception as e:
logging.error(f"Weekly task failed: {str(e)}", exc_info=True)
if __name__ == '__main__':
scheduler = BlockingScheduler()
# 0 8 * * 0 maps to minute=0, hour=8, day_of_week='sun'
trigger = CronTrigger(minute=0, hour=8, day_of_week='sun', timezone='UTC')
scheduler.add_job(execute_weekly_job, trigger=trigger, id='weekly_maintenance')
logging.info("Weekly scheduler started. Waiting for Sunday 08:00 UTC...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logging.info("Scheduler stopped cleanly.") › Setup notes
Install 'apscheduler' via pip, then run the daemon script with 'python scheduler.py' to keep the background scheduler active.
// Go implementation using robfig/cron/v3
// Run: go get github.com/robfig/cron/v3
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "[WeeklyJob] ", log.LstdFlags|log.LUTC)
logger.Println("Initializing cron engine...")
// Ensure we use UTC to avoid local timezone/DST shifts
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 8 * * 0", func() {
logger.Println("Execution started.")
if err := runWeeklyTask(); err != nil {
logger.Printf("CRITICAL ERROR: Job failed: %v\n", err)
return
}
logger.Println("Execution completed successfully.")
})
if err != nil {
logger.Fatalf("Failed to schedule job: %v", err)
}
c.Start()
logger.Println("Scheduler running. Press Ctrl+C to exit.")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down scheduler gracefully...")
c.Stop()
}
func runWeeklyTask() error {
time.Sleep(2 * time.Second)
return nil
} › Setup notes
Ensure your project has the robfig/cron library imported, build the binary using 'go build', and deploy it to run as a system daemon.
// Java Spring Boot Scheduler implementation
package com.example.cron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class WeeklyMaintenanceScheduler {
private static final Logger logger = LoggerFactory.getLogger(WeeklyMaintenanceScheduler.class);
// Spring cron format uses 6 fields: second, minute, hour, day-of-month, month, day-of-week
@Scheduled(cron = "0 0 8 * * SUN", zone = "UTC")
public void runWeeklyJob() {
logger.info("Weekly cron job triggered at 08:00 UTC on Sunday.");
try {
performMaintenance();
logger.info("Weekly cron job completed successfully.");
} catch (Exception e) {
logger.error("Error occurred during weekly maintenance job execution", e);
}
}
private void performMaintenance() throws Exception {
Thread.sleep(1000); // Mock processing block
}
} › Setup notes
Add the '@EnableScheduling' annotation to your main Spring Boot Application class and register this component in your project configuration.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekly-system-maintenance
namespace: production
labels:
app: weekly-maintenance
spec:
schedule: "0 8 * * 0"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
startingDeadlineSeconds: 1800
jobTemplate:
spec:
template:
metadata:
labels:
app: weekly-maintenance
spec:
containers:
- name: maintenance-worker
image: busybox:1.36
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- |
echo "Starting weekly maintenance job..."
sleep 30
echo "Weekly maintenance completed successfully."
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
restartPolicy: OnFailure › Setup notes
Apply this configuration to your cluster using 'kubectl apply -f cronjob.yaml' and verify the schedule with 'kubectl get cronjobs -n production'.
Last verified:
Monitor this schedule in production
Get alerted the moment this cron job fails, is late, or doesn't run. BetterStack tracks execution, duration, and output — no infrastructure required.
Platform Equivalents
AWS EventBridge
Standard cron expressions often need conversion for AWS EventBridge schedules.
cron(0 8 ? * 0 *) Systemd Timer
OnCalendarSun *-*-* 08:00:00
[Unit]
Description=Timer for cron expression: 0 8 * * 0
[Timer]
OnCalendar=Sun *-*-* 08:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How does Daylight Saving Time affect this Sunday 8 AM schedule?
Since the schedule runs at 8:00 AM, it is safely past the typical 2:00 AM DST shift. However, if your system clock shifts, the interval from the previous run may be 167 or 169 hours instead of 168. Ensure your cron daemon or scheduler is timezone-aware (using UTC is highly recommended) to avoid unexpected execution timing.
Is Sunday represented by 0 or 7 in standard cron systems?
In standard POSIX cron, 0 represents Sunday. However, many modern implementations (such as Vixie cron, BSD cron, and systemd) accept both 0 and 7 to represent Sunday. Using 0 is the most universally portable configuration across older legacy Unix environments.
What happens if the server is powered down at Sunday 8:00 AM?
Standard cron does not catch up on missed executions. If your server is offline at 8:00 AM on Sunday, the job will not run until the following Sunday. To mitigate this risk, use a utility like anacron for system tasks, or implement an external monitoring tool that alerts you when an expected weekly heartbeat is missed.
How should I handle long-running tasks scheduled at this time?
Since this job runs once a week, it has a large execution window before the next scheduled run. However, to prevent resource exhaustion or overlapping processes, wrap your script in a file lock utility like flock in Linux, or set a strict timeout within your application code.
Can I run this job on both Saturday and Sunday at 8:00 AM?
Yes, you can modify the day-of-week field to include both days. The expression '0 8 * * 0,6' or '0 8 * * 6-0' (depending on the parser) will trigger the execution at 8:00 AM on both Saturday (6) and Sunday (0), allowing you to run weekend-specific workflows.
* Explore
Related expressions you might need
Last verified: