Weekly Sunday Midnight Cron Schedule | CronBase
0 0 * * 0 Every Sunday at midnight
The `0 0 * * 0` cron expression triggers a scheduled task weekly on Sundays at exactly midnight (00:00). This predictable, low-traffic time slot is widely utilized by systems administrators and DevOps teams for executing resource-intensive operations like full database backups, log rotations, SSL certificate renewals, and system cleanup scripts.
- Minute
- 0
- Hour
- 0
- Day of Month
- *
- Month
- *
- Day of Week
- 0
Next 5 Runs
- in 3h 34m
- in 7d 3h
- in 14d 3h
- in 21d 3h
- in 28d 3h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Weekly maintenance script designed to run via cron: 0 0 * * 0
set -euo pipefail
LOCKFILE="/var/lock/weekly-cleanup.lock"
LOGFILE="/var/log/weekly-cleanup.log"
# Ensure only one instance runs at a time
exec 9>"$LOCKFILE"
if ! flock -n 9; then
echo "$(date -u) - ERROR: Another instance is already running." >&2
exit 1
fi
echo "$(date -u) - Starting weekly database maintenance..." >> "$LOGFILE"
# Perform backup; redirect stderr to logfile
if pg_dump -U postgres -h localhost my_db > /backups/db_weekly_$(date +%F).sql 2>> "$LOGFILE"; then
echo "$(date -u) - Weekly backup completed successfully." >> "$LOGFILE"
else
echo "$(date -u) - CRITICAL: Weekly backup failed!" >&2
exit 1
fi › Setup notes
Save the code as weekly-cleanup.sh, run chmod +x weekly-cleanup.sh, and add it to your crontab using crontab -e with the line: 0 0 * * 0 /path/to/weekly-cleanup.sh.
const { CronJob } = require('cron');
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [new winston.transports.Console()]
});
// Schedule for 0 0 * * 0 (Every Sunday at midnight UTC)
const job = new CronJob(
'0 0 * * 0',
async function() {
logger.info('Starting weekly data aggregation task...');
try {
await performWeeklyAggregation();
logger.info('Weekly data aggregation completed successfully.');
} catch (error) {
logger.error('Failed to execute weekly aggregation job:', error);
}
},
null,
true,
'UTC'
);
async function performWeeklyAggregation() {
// Simulate async processing logic
return new Promise((resolve) => setTimeout(resolve, 5000));
}
job.start(); › Setup notes
Install the dependencies using npm install cron winston. Run this script using node weekly-job.js inside a process manager like PM2 to guarantee uptime.
import logging
import sys
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 run_weekly_cleanup():
logging.info("Initiating weekly log rotation and cache eviction...")
try:
# Cleanup execution logic
logging.info("Weekly cleanup successfully executed.")
except Exception as e:
logging.error(f"Weekly cleanup failed: {str(e)}", exc_info=True)
if __name__ == "__main__":
scheduler = BlockingScheduler()
# 0 0 * * 0 translates to day_of_week='sun', hour=0, minute=0
trigger = CronTrigger(day_of_week='sun', hour=0, minute=0, timezone='UTC')
scheduler.add_job(run_weekly_cleanup, trigger=trigger, id='weekly_job')
logging.info("Starting scheduler. Job scheduled for every Sunday at 00:00 UTC.")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logging.info("Scheduler stopped.") › Setup notes
Install APScheduler using pip install apscheduler. Run the Python script to start the scheduler daemon, which runs continuously in the background.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "[WeeklyJob] ", log.LstdFlags|log.LUTC)
// Create cron scheduler with UTC timezone enforcement
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 0 * * 0", func() {
logger.Println("Starting weekly backup and sync routine...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
if err := executeBackup(ctx); err != nil {
logger.Printf("CRITICAL: Weekly backup failed: %v\n", err)
} else {
logger.Println("Weekly backup completed successfully.")
}
})
if err != nil {
logger.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
logger.Println("Cron runner started. Job scheduled for Sunday midnight UTC.")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down cron runner...")
c.Stop()
}
func executeBackup(ctx context.Context) error {
select {
case <-time.After(5 * time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
} › Setup notes
Fetch the cron dependency using go get github.com/robfig/cron/v3. Compile and run the binary to start the long-running scheduling daemon.
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 syntax: second, minute, hour, day-of-month, month, day-of-week
// Equivalent to standard cron: 0 0 * * 0
@Scheduled(cron = "0 0 0 * * SUN", zone = "UTC")
public void executeWeeklyMaintenance() {
logger.info("Weekly maintenance cycle started at Sunday midnight UTC.");
try {
purgeExpiredSessions();
optimizeDatabaseIndices();
logger.info("Weekly maintenance cycle completed successfully.");
} catch (Exception ex) {
logger.error("CRITICAL: Weekly maintenance failed", ex);
}
}
private void purgeExpiredSessions() {
logger.info("Purging expired sessions...");
}
private void optimizeDatabaseIndices() {
logger.info("Optimizing database indices...");
}
} › Setup notes
Ensure @EnableScheduling is added to your Spring Boot main class config. Spring will automatically detect this component and run it at Sunday midnight UTC.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekly-database-vacuum
namespace: database
spec:
schedule: "0 0 * * 0"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
startingDeadlineSeconds: 1800
jobTemplate:
spec:
template:
spec:
containers:
- name: db-vacuum-client
image: postgres:15-alpine
command:
- /bin/sh
- -c
- |
echo "Starting database vacuuming..."
vacuumdb -U postgres -h db-service.database.svc.cluster.local -a -v || exit 1
echo "Vacuuming complete."
env:
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
restartPolicy: OnFailure › Setup notes
Save the manifest as cronjob-weekly.yaml and apply it to your cluster using kubectl apply -f cronjob-weekly.yaml. This ensures tasks do not overlap if they run past midnight.
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 ? * 0 *) Systemd Timer
OnCalendarSun *-*-* 00:00:00
[Unit]
Description=Timer for cron expression: 0 0 * * 0
[Timer]
OnCalendar=Sun *-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How does DST affect the Sunday midnight execution?
If your system runs on local time zones that observe Daylight Saving Time, the transition usually occurs on Sunday mornings (e.g., at 2:00 AM). While Sunday midnight (00:00) is before most DST transitions, some regions shift at midnight, causing the job to either run twice or skip. It is highly recommended to use UTC to avoid these issues.
How can I prevent multiple instances of this weekly cron from running simultaneously?
For standard Unix systems, wrap your script execution with the `flock` utility to enforce a file lock. In Kubernetes, set the `concurrencyPolicy` to `Forbid` within the CronJob specification. In application-level schedulers, use distributed lock managers like Redis (Redlock) or database-backed locks.
What is the best way to test a cron job scheduled for Sunday midnight?
You should decouple the execution logic from the schedule. Write your logic as a standalone script or command-line task, then manually trigger it in a staging environment. To test the cron configuration itself, temporarily change the expression to run every few minutes (e.g., `*/5 * * * *`) to verify the scheduler hooks work.
How do I handle failures in a weekly cron job without waiting another week?
Implement robust monitoring and alerting using tools like Prometheus Alertmanager or Sentry. If a job fails, the system must trigger an immediate notification to your on-call team. Ensure your architecture allows you to manually trigger the job on-demand to rerun failed operations safely.
Should I run database migrations on this Sunday midnight schedule?
While Sunday midnight has low traffic, using standard cron for database migrations is dangerous. Migrations should be tightly integrated with your deployment pipeline (CI/CD) and executed as pre-deployment or post-deployment steps with rolling updates, rather than decoupled time-based schedulers.
* Explore
Related expressions you might need
Last verified: