Run Weekly Tasks Every Monday at Midnight | CronBase
0 0 * * 1 Every single week at midnight on Monday morning
This standard cron expression schedules a task to execute every Monday at exactly midnight (00:00). It is widely used in production environments for weekly system maintenance, database indexing, log rotation, and generating business analytics reports before teams begin their workweek, ensuring clean system states and updated dashboards.
- Minute
- 0
- Hour
- 0
- Day of Month
- *
- Month
- *
- Day of Week
- 1
Next 5 Runs
- in 1d 3h
- in 8d 3h
- in 15d 3h
- in 22d 3h
- in 29d 3h
* Tools
Code & Implementations
#!/usr/bin/env bash
set -euo pipefail
# Operational cron script for weekly backup/maintenance
LOCKFILE="/var/lock/weekly_maintenance.lock"
exec 200>"$LOCKFILE"
if ! flock -n 200; then
echo "Error: Another instance of this weekly job is already running." >&2
exit 1
fi
echo "[$(date -u)] Starting weekly maintenance task..."
# Add production business logic here
# Example: tar -czf /backups/weekly_$(date +%F).tar.gz /data
echo "[$(date -u)] Weekly maintenance completed successfully." › Setup notes
Save this script to /usr/local/bin/weekly_maintenance.sh, make it executable using 'chmod +x', and add the cron entry using 'crontab -e' targeting '0 0 * * 1'.
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule: 0 0 * * 1 (Every Monday at midnight)
cron.schedule('0 0 * * 1', async () => {
console.log(`[${new Date().toISOString()}] Initiating weekly cleanup task...`);
try {
await runWeeklyTask();
console.log(`[${new Date().toISOString()}] Weekly task finished successfully.`);
} catch (error) {
console.error(`[${new Date().toISOString()}] Critical failure during weekly task:`, error);
// In production, integrate with PagerDuty, Sentry, or Slack webhook alert here
}
});
function runWeeklyTask() {
return new Promise((resolve, reject) => {
// Mock database optimization or cleanup
setTimeout(() => resolve(), 5000);
});
} › Setup notes
Install node-cron via 'npm install node-cron'. Run this persistent Node process using a process manager like PM2 to guarantee continuous scheduling.
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')
logger = logging.getLogger(__name__)
def execute_weekly_job():
logger.info("Starting scheduled weekly data reconciliation pipeline...")
try:
# Insert core business logic here (e.g., DB vacuuming, report compilation)
logger.info("Weekly data reconciliation completed successfully.")
except Exception as e:
logger.error(f"Failed to execute weekly job: {str(e)}", exc_info=True)
# Production environments should raise alerts to external monitoring systems here
if __name__ == "__main__":
scheduler = BlockingScheduler()
# Standard cron syntax: 0 0 * * 1 mapped to CronTrigger
trigger = CronTrigger(day_of_week='mon', hour=0, minute=0, timezone='UTC')
scheduler.add_job(execute_weekly_job, trigger=trigger, id='weekly_reconciliation')
logger.info("Scheduler initialized. Waiting for Monday midnight UTC trigger...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped cleanly.")
sys.exit(0) › Setup notes
Install APScheduler via 'pip install apscheduler'. Run the script inside a systemd service or container to maintain execution state.
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.Lshortfile)
// Initialize cron runner with UTC location to prevent DST confusion
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 0 * * 1", func() {
logger.Println("Executing weekly database index optimization...")
err := performMaintenance()
if err != nil {
logger.Printf("CRITICAL ERROR during weekly maintenance: %v\n", err)
// Integrate alert/pager notification here
return
}
logger.Println("Weekly database optimization completed successfully.")
})
if err != nil {
logger.Fatalf("Failed to initialize cron job: %v", err)
}
c.Start()
logger.Println("Scheduler started. Monitoring for weekly Monday 00:00 UTC execution...")
// Keep application running until interrupted
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down scheduler...")
c.Stop()
}
func performMaintenance() error {
// Simulating production maintenance task
time.Sleep(2 * time.Second)
return nil
} › Setup notes
Fetch the dependency using 'go get github.com/robfig/cron/v3'. Compile the binary and execute it on your host platform.
package com.cronbase.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);
/**
* Schedules the weekly maintenance task.
* Cron syntax: "0 0 0 * * MON" in Spring (seconds, minutes, hours, day-of-month, month, day-of-week)
* Zone is explicitly set to UTC to guarantee stable execution across different infrastructure environments.
*/
@Scheduled(cron = "0 0 0 * * MON", zone = "UTC")
public void runWeeklyMaintenance() {
logger.info("Initiating weekly security audit and log rotation process...");
try {
executeAuditSuite();
logger.info("Weekly security audit and log rotation completed successfully.");
} catch (Exception ex) {
logger.error("CRITICAL: Weekly maintenance task failed!", ex);
// Production recommendation: Trigger external incident management integration (e.g., Opsgenie)
}
}
private void executeAuditSuite() throws Exception {
// Simulate business logic execution
Thread.sleep(1000);
}
} › Setup notes
Ensure '@EnableScheduling' is declared on your main Spring Boot configuration class, and this class is scanned as a Spring Component.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekly-database-cleanup
namespace: production
spec:
# Run every Monday at midnight (00:00)
schedule: "0 0 * * 1"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
startingDeadlineSeconds: 1800
jobTemplate:
spec:
template:
spec:
containers:
- name: maintenance-worker
image: postgres:15-alpine
command:
- /bin/sh
- -c
- |
echo "Starting weekly database vacuuming..."
vacuumdb -U postgres -h db-service.production.svc.cluster.local -a -z || exit 1
echo "Weekly database vacuuming completed successfully."
env:
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
restartPolicy: OnFailure › Setup notes
Apply this manifest using 'kubectl apply -f cronjob.yaml'. Ensure the namespace and secrets are configured correctly beforehand.
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 ? * 1 *) Systemd Timer
OnCalendarMon *-*-* 00:00:00
[Unit]
Description=Timer for cron expression: 0 0 * * 1
[Timer]
OnCalendar=Mon *-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I handle daylight saving time changes with this weekly schedule?
To prevent duplicate or skipped executions during daylight saving time (DST) shifts, configure your cron daemon or orchestrator to run in Coordinated Universal Time (UTC). If local time is required, use a modern scheduler like systemd-timer or Kubernetes CronJobs that natively handles DST transitions.
What happens if the server is offline at Monday midnight?
Standard cron daemons will skip the execution entirely if the server is offline at the scheduled time. If guaranteed execution is critical, use tools like `anacron` on Linux, or implement idempotent jobs with a queue-based scheduler that triggers missed runs upon system startup.
How can I prevent multiple weekly jobs from overloading the database at this time?
Implement a randomized startup delay or jitter (e.g., sleeping for a random duration between 1 and 10 minutes) at the beginning of your job execution. This distributes the database load and prevents resource contention from concurrent cron tasks.
Is it safe to use this schedule for log rotation?
Yes, this is a common pattern for weekly log rotation. However, ensure that logrotate or your custom script has a lock mechanism (such as `flock`) to prevent concurrent instances from running if a previous rotation hangs, and verify that services are gracefully reloaded to release file handles.
How does standard cron interpret the day-of-week field value of 1?
In the standard cron specification, the day-of-week field value of 1 represents Monday. Note that while 0 and 7 both represent Sunday in many modern implementations, 1 consistently and unambiguously represents Monday across all standard UNIX platforms.
* Explore
Related expressions you might need
Last verified: