Run Daily Backups and Syncs at 10 PM | CronBase
0 22 * * * Every day in the evening at ten PM
The `0 22 * * *` cron expression triggers a scheduled task every day at exactly 10:00 PM (22:00) in the system's local timezone. It is widely used in production environments for executing nightly database backups, processing daily batch transactions, rotating system logs, and initiating off-peak synchronization tasks before the midnight rollover.
- Minute
- 0
- Hour
- 22
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 1h 19m
- in 1d 1h
- in 2d 1h
- in 3d 1h
- in 4d 1h
* Tools
Code & Implementations
# Edit your crontab using: crontab -e
# Standard cron entry to run a backup script at 10:00 PM daily
# Uses flock to prevent overlapping executions and redirects output to a log file
0 22 * * * /usr/bin/flock -n /var/run/daily_backup.lck /usr/local/bin/daily_backup.sh >> /var/log/cron/daily_backup.log 2>&1 › Setup notes
Open your user crontab using crontab -e and paste the entry. Ensure the log directory /var/log/cron/ exists and the execution script has run permissions (chmod +x).
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule task to run daily at 22:00 (10:00 PM)
cron.schedule('0 22 * * *', () => {
console.log(`[${new Date().toISOString()}] Starting nightly database backup...`);
exec('/usr/local/bin/backup-db.sh', (error, stdout, stderr) => {
if (error) {
console.error(`[ERROR] Backup failed: ${error.message}`);
return;
}
if (stderr) {
console.warn(`[WARN] Backup stderr: ${stderr}`);
}
console.log(`[SUCCESS] Backup completed. Output: ${stdout}`);
});
}, {
scheduled: true,
timezone: "Etc/UTC"
}); › Setup notes
Install the dependency using npm install node-cron. Run this background process using a process manager like PM2 to guarantee constant uptime.
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def run_nightly_sync():
logging.info("Starting nightly synchronization task...")
try:
# Core business logic or subprocess call goes here
pass
logging.info("Nightly synchronization task completed successfully.")
except Exception as e:
logging.error(f"Task failed with error: {e}", exc_info=True)
if __name__ == "__main__":
scheduler = BlockingScheduler()
# Trigger daily at 22:00 (10:00 PM)
scheduler.add_job(run_nightly_sync, 'cron', hour=22, minute=0, timezone='UTC')
logging.info("Scheduler started. Waiting for 22:00 UTC...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logging.info("Scheduler stopped cleanly.") › Setup notes
Install the required package via pip install apscheduler. Run the script in your terminal or containerized environment to monitor the schedule.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
// Initialize cron with UTC location to ensure consistent execution
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 22 * * *", func() {
log.Println("Starting scheduled daily cleanup job at 22:00 UTC...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
if err := executeCleanup(ctx); err != nil {
log.Printf("Error during cleanup: %v", err)
} else {
log.Println("Daily cleanup job finished successfully.")
}
})
if err != nil {
log.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
log.Println("Cron scheduler initiated. Waiting for daily 22:00 execution...")
// Graceful shutdown handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Stopping cron scheduler...")
c.Stop()
}
func executeCleanup(ctx context.Context) error {
// Simulate background execution work
time.Sleep(5 * time.Second)
return nil
} › Setup notes
Fetch the cron library using go get github.com/robfig/cron/v3. Compile and run the binary in your production daemon environment.
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 NightlyTaskScheduler {
private static final Logger logger = LoggerFactory.getLogger(NightlyTaskScheduler.class);
// Spring cron format uses 6 fields: second, minute, hour, day, month, day-of-week
// Runs at 22:00:00 (10 PM) every day in UTC
@Scheduled(cron = "0 0 22 * * *", zone = "UTC")
public void executeNightlyJob() {
logger.info("Executing scheduled nightly data reconciliation job...");
try {
performReconciliation();
logger.info("Nightly reconciliation job completed successfully.");
} catch (Exception e) {
logger.error("Critical failure during nightly reconciliation job", e);
}
}
private void performReconciliation() throws Exception {
// Simulate work execution
Thread.sleep(10000);
}
} › Setup notes
Ensure @EnableScheduling is added to your Spring Boot application's configuration class. The @Scheduled annotation will automatically configure the bean runtime.
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-cleanup-job
namespace: default
spec:
schedule: "0 22 * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
template:
spec:
containers:
- name: cleanup-worker
image: busybox:1.36
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- "echo 'Starting daily system cleanup...'; sleep 30; echo 'Cleanup completed successfully!'"
resources:
limits:
cpu: "500m"
memory: "256Mi"
requests:
cpu: "100m"
memory: "128Mi"
restartPolicy: OnFailure › Setup notes
Apply the manifest to your cluster using kubectl apply -f manifest.yaml. Monitor the execution status of active pods using kubectl get cronjob.
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 22 * * ? *) Systemd Timer
OnCalendar*-*-* 22:00:00
[Unit]
Description=Timer for cron expression: 0 22 * * *
[Timer]
OnCalendar=*-*-* 22:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How does Daylight Saving Time (DST) affect a 10 PM daily cron job?
Depending on your OS timezone database, DST shifts can cause the job to run an hour early or late relative to UTC, or potentially skip/double-execute if transitioning during that hour. Running your system clock on UTC is the industry standard to ensure consistent 24-hour intervals.
Can I run this job only on weekdays instead of every day?
Yes, you can modify the fifth field (day-of-week) to restrict execution. Changing the expression to `0 22 * * 1-5` will run the task at 10 PM Monday through Friday, skipping Saturday and Sunday.
What happens if the server is offline at 10 PM when the job is scheduled?
Standard cron does not catch up on missed executions. If your server is offline at 22:00, the job will not run until 10 PM the following day. For critical tasks, use utilities like anacron or implement a startup check script.
How do I prevent multiple instances of this 10 PM job from overlapping?
Use a locking mechanism like `flock` in Linux, or a distributed lock manager like Redis (Redlock) if running across multiple nodes. This ensures that if the previous day's task is still running, the new instance terminates safely.
Why is my 10 PM cron job running at 5 PM local time?
This discrepancy occurs because your server's system clock is configured to UTC (or a different timezone) rather than your local timezone. Check your system time using the `date` command and adjust either the server timezone or the cron hour accordingly.
* Explore
Related expressions you might need
Last verified: