Run Weekend Midnight Maintenance Tasks | CronBase
0 0 * * 6,0 Every Saturday and Sunday at midnight.
This cron expression schedules a task to run at exactly midnight (00:00) every Saturday and Sunday. It is commonly used by system administrators and DevOps engineers to perform weekly maintenance, database optimization, and system backups during low-traffic weekend windows to avoid impacting production users.
- Minute
- 0
- Hour
- 0
- Day of Month
- *
- Month
- *
- Day of Week
- 6,0
Next 5 Runs
- in 3h 33m
- in 6d 3h
- in 7d 3h
- in 13d 3h
- in 14d 3h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Cron execution: 0 0 * * 6,0 (Midnight on Saturday and Sunday)
set -euo pipefail
LOCKFILE="/var/lock/weekend_maintenance.lock"
exec 9>"$LOCKFILE"
if ! flock -n 9; then
echo "Error: Another instance of the weekend maintenance job is already running." >&2
exit 1
fi
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Starting weekend maintenance..."
if ! tar -czf /backup/db_weekend_$(date +%F).tar.gz /var/lib/mysql; then
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Backup failed!" >&2
exit 1
fi
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Weekend maintenance completed successfully." › Setup notes
Save this script to /usr/local/bin/weekend-maint.sh, make it executable with chmod +x, and configure it under the root crontab using 'crontab -e'.
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule task for midnight on Saturday (6) and Sunday (0)
cron.schedule('0 0 * * 6,0', () => {
console.log(`[${new Date().toISOString()}] Initiating weekend database cleanup...`);
exec('npm run db:cleanup', (error, stdout, stderr) => {
if (error) {
console.error(`[ERROR] Cleanup failed: ${error.message}`);
return;
}
if (stderr) {
console.warn(`[WARN] Cleanup stderr: ${stderr}`);
}
console.log(`[SUCCESS] Cleanup output: ${stdout}`);
});
}, {
scheduled: true,
timezone: "UTC"
}); › Setup notes
Install node-cron using 'npm install node-cron' and run this script as a background service using PM2 or Docker.
import logging
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def execute_weekend_task():
logger.info("Starting weekend maintenance job...")
try:
# Simulated maintenance task
logger.info("Database optimization completed successfully.")
except Exception as e:
logger.error(f"Weekend maintenance job failed: {str(e)}")
if __name__ == "__main__":
scheduler = BlockingScheduler()
# 0 0 * * 6,0 translates to day_of_week='sat,sun' at hour=0, minute=0
scheduler.add_job(execute_weekend_task, 'cron', day_of_week='sat,sun', hour=0, minute=0, timezone='UTC')
logger.info("Scheduler started. Waiting for Saturday/Sunday midnight...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped.") › Setup notes
Install the required APScheduler package via 'pip install apscheduler' and run the script inside a persistent virtual environment.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "[WeekendCron] ", log.LstdFlags|log.Lshortfile)
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 0 * * 6,0", func() {
logger.Println("Starting scheduled weekend maintenance...")
err := runMaintenance()
if err != nil {
logger.Printf("ERROR: Maintenance task failed: %v", err)
return
}
logger.Println("Maintenance task completed successfully.")
})
if err != nil {
logger.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
logger.Println("Cron scheduler started...")
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
logger.Println("Stopping scheduler...")
c.Stop()
}
func runMaintenance() error {
// Simulate work
time.Sleep(2 * time.Second)
return nil
} › Setup notes
Initialize a Go module, run 'go get github.com/robfig/cron/v3' to fetch the dependency, and compile the binary for production deployment.
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 WeekendMaintenanceScheduler {
private static final Logger logger = LoggerFactory.getLogger(WeekendMaintenanceScheduler.class);
// Spring cron format: second, minute, hour, day of month, month, day of week
@Scheduled(cron = "0 0 0 * * SAT,SUN", zone = "UTC")
public void runWeekendMaintenance() {
logger.info("Initiating scheduled weekend maintenance job...");
try {
performMaintenance();
logger.info("Weekend maintenance completed successfully.");
} catch (Exception e) {
logger.error("Error occurred during weekend maintenance: ", e);
}
}
private void performMaintenance() throws Exception {
// Logic for heavy operations (e.g., clearing caches, compressing tables)
Thread.sleep(5000);
}
} › Setup notes
Ensure @EnableScheduling is annotated on your main Spring Boot Application class to activate the scheduled runner.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekend-maintenance-job
namespace: default
spec:
schedule: "0 0 * * 6,0"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
template:
spec:
containers:
- name: maintenance-worker
image: postgres:15-alpine
command:
- /bin/sh
- -c
- |
echo "Starting weekend PG database vacuum..."
vacuumdb -U postgres -h db-service -a -v || exit 1
echo "Database vacuum completed successfully."
restartPolicy: OnFailure › Setup notes
Apply this configuration to your Kubernetes cluster using 'kubectl apply -f cronjob.yaml'. Ensure service accounts have appropriate DB network access.
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 0 ? * 6,0 *) Systemd Timer
OnCalendarSat,Sun *-*-* 00:00:00
[Unit]
Description=Timer for cron expression: 0 0 * * 6,0
[Timer]
OnCalendar=Sat,Sun *-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
Does standard cron treat 0 and 7 both as Sunday?
Yes, in most standard cron implementations (such as Vixie cron, commonly found in Linux), both 0 and 7 represent Sunday. However, to guarantee maximum portability across different systems and cloud platforms, using 0 is widely preferred.
What happens if Saturday's run takes longer than 24 hours to complete?
If Saturday's run exceeds 24 hours, Sunday's run will trigger while the previous execution is still active. To prevent race conditions and system overload, you should implement lock files, use `flock` in Bash, or set `concurrencyPolicy: Forbid` in Kubernetes.
How do daylight saving time (DST) transitions affect this midnight schedule?
If your system timezone is configured to a local timezone that observes DST, your job might run twice or be skipped entirely when clocks shift. To avoid this unpredictable behavior, it is highly recommended to configure your system or application schedulers to run strictly in UTC.
Can I target only Saturday instead of both weekend days?
Yes, if you want to run the job exclusively on Saturday, you can modify the day-of-week field to only include 6. The resulting cron expression would be `0 0 * * 6`.
Why is this schedule preferred over daily midnight maintenance?
Running tasks on weekends minimizes the risk of impacting active users, as standard business application traffic is typically at its lowest. This provides a safer window for executing heavy locking operations, schema migrations, or massive data aggregations that could degrade system performance during weekdays.
* Explore
Related expressions you might need
Last verified: