Run Weekly Saturday Midnight Backups | CronBase
0 0 * * 6 Every Saturday at midnight
The `0 0 * * 6` cron expression schedules a task to run once a week at exactly midnight every Saturday. It is commonly used in production environments for heavy weekly maintenance jobs, database optimization, full system backups, and generating weekly analytical reports during low-traffic weekend hours.
- Minute
- 0
- Hour
- 0
- Day of Month
- *
- Month
- *
- Day of Week
- 6
Next 5 Runs
- in 6d 3h
- in 13d 3h
- in 20d 3h
- in 27d 3h
- in 34d 3h
* Tools
Code & Implementations
#!/usr/bin/env bash
set -euo pipefail
# Production Saturday Midnight Backup Script
BACKUP_DIR="/var/backups/weekly"
LOG_FILE="/var/log/weekly_backup.log"
exec > >(tee -ia "$LOG_FILE") 2>&1
echo "[$(date -u)] Starting weekly backup execution..."
if ! mkdir -p "$BACKUP_DIR"; then
echo "Error: Failed to create backup directory" >&2
exit 1
fi
# Simulate backup logic with error handling
if tar -czf "$BACKUP_DIR/data-$(date +%F).tar.gz" /data/db; then
echo "[$(date -u)] Weekly backup completed successfully."
else
echo "Error: Weekly backup failed!" >&2
exit 1
fi › Setup notes
Save this script to /usr/local/bin/weekly-backup.sh, make it executable with chmod +x, and add 0 0 * * 6 /usr/local/bin/weekly-backup.sh to the root crontab using crontab -e.
const cron = require('cron');
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [new winston.transports.Console()]
});
// Cron pattern for every Saturday at midnight
const job = new cron.CronJob('0 0 * * 6', async () => {
logger.info('Starting scheduled weekly database maintenance...');
try {
// Perform database optimization and cleanup
await performWeeklyMaintenance();
logger.info('Weekly maintenance completed successfully.');
} catch (error) {
logger.error('Failed to execute weekly maintenance:', error);
}
}, null, true, 'UTC');
async function performWeeklyMaintenance() {
// Production-ready maintenance logic here
return Promise.resolve();
}
job.start(); › Setup notes
Install the cron and winston packages using npm install cron winston. Run this script as a daemon utilizing a process manager like PM2 to guarantee continuous scheduling.
import logging
import sys
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)
def run_weekly_pipeline():
logger.info("Starting weekly data pipeline execution...")
try:
# Implement production data pipeline or cleanup logic
logger.info("Weekly data pipeline completed successfully.")
except Exception as e:
logger.error(f"Critical failure in weekly data pipeline: {str(e)}", exc_info=True)
# In production, trigger external alerts here
scheduler = BlockingScheduler(timezone="UTC")
# 0 0 * * 6 translates to Saturday
scheduler.add_job(run_weekly_pipeline, 'cron', day_of_week='sat', hour=0, minute=0)
if __name__ == "__main__":
try:
logger.info("Starting scheduler for Saturday midnight job...")
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped.") › Setup notes
Install APScheduler using pip install apscheduler. Run this Python script inside a systemd service to ensure it starts on boot and runs continuously in the background.
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)
nyc, err := time.LoadLocation("UTC")
if err != nil {
logger.Fatalf("Failed to load timezone: %v", err)
}
c := cron.New(cron.WithLocation(nyc))
_, err = c.AddFunc("0 0 * * 6", func() {
logger.Println("Starting weekly data sync...")
if err := executeWeeklySync(); err != nil {
logger.Printf("ERROR: Weekly sync failed: %v", err)
} else {
logger.Println("Weekly sync finished successfully.")
}
})
if err != nil {
logger.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
logger.Println("Scheduler started successfully.")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down gracefully...")
c.Stop()
}
func executeWeeklySync() error {
// Production sync logic goes here
return nil
} › Setup notes
Initialize your Go module, fetch the cron library using go get github.com/robfig/cron/v3, and build the binary using go build -o scheduler main.go.
package com.example.scheduler;
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 expression: second, minute, hour, day of month, month, day(s) of week
@Scheduled(cron = "0 0 0 * * SAT", zone = "UTC")
public void runWeeklyMaintenance() {
logger.info("Starting scheduled weekly system maintenance...");
try {
executeMaintenanceTasks();
logger.info("Weekly system maintenance completed successfully.");
} catch (Exception e) {
logger.error("Critical error during weekly system maintenance", e);
}
}
private void executeMaintenanceTasks() throws Exception {
// Business logic for weekly cleanup
}
} › Setup notes
Ensure @EnableScheduling is added to your main Spring Boot Application class. Spring will automatically discover this component and register the scheduled task.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekly-database-cleanup
namespace: production
spec:
schedule: "0 0 * * 6"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: db-cleaner
image: postgres:15-alpine
command:
- /bin/sh
- -c
- "vacuumdb -U postgres -d main_db --analyze --verbose"
env:
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
resources:
limits:
cpu: "1"
memory: 1Gi
requests:
cpu: "500m"
memory: 512Mi › Setup notes
Apply this manifest using kubectl apply -f weekly-cronjob.yaml. The spec enforces a concurrency policy of Forbid to prevent overlapping executions and keeps a history of successful and failed executions for debugging.
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 0 ? * 6 *) Systemd Timer
OnCalendarSat *-*-* 00:00:00
[Unit]
Description=Timer for cron expression: 0 0 * * 6
[Timer]
OnCalendar=Sat *-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How does Daylight Saving Time (DST) affect the Saturday midnight execution?
Depending on your system's timezone, a DST transition can cause the job to run twice or not at all if it occurs on that night. To prevent this, configure your cron daemon or scheduler to run on UTC.
What happens if a previous week's execution is still running when the next Saturday comes?
For standard cron, the job will spawn concurrently, potentially causing race conditions. Use locking mechanisms like `flock` in Bash, or set `concurrencyPolicy: Forbid` in Kubernetes to prevent overlapping.
Can I run this job on Friday night instead of Saturday night?
Yes, you can change the day-of-week field from `6` (Saturday) to `5` (Friday). The expression would then be `0 0 * * 5`, executing at midnight as Friday transitions to Saturday.
How should I monitor a weekly job to ensure it actually ran?
Since weekly jobs run infrequently, passive logging is insufficient. Use a push-based monitoring system ("Dead Man's Snitch") where the job pings an external service on completion; if no ping is received by 00:15 Saturday, an alert is raised.
Is there a way to run the job at 2:00 AM on Saturday instead of midnight?
Yes, modifying the hour field from `0` to `2` changes the execution time. The expression `0 2 * * 6` is often preferred to avoid resource contention with other midnight-scheduled tasks.
* Explore
Related expressions you might need
Last verified: