Run Nightly Weekday Jobs at 10 PM | CronBase
0 22 * * 1-5 Every night from Monday through Friday at ten o'clock in the evening.
The `0 22 * * 1-5` cron expression schedules a task to run automatically every weekday night, from Monday through Friday, precisely at 10:00 PM. It is commonly used in enterprise environments to trigger end-of-day database backups, synchronize transactional data, and clean up temporary storage volumes after business hours.
- Minute
- 0
- Hour
- 22
- Day of Month
- *
- Month
- *
- Day of Week
- 1-5
Next 5 Runs
- in 2d 1h
- in 3d 1h
- in 4d 1h
- in 5d 1h
- in 6d 1h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Safe installation script for the weekday 10 PM cron job.
set -euo pipefail
# Define the cron command to execute safely
CRON_CMD="0 22 * * 1-5 /usr/local/bin/backup-job.sh >> /var/log/backup-job.log 2>&1"
# Verify script exists before registering
if [ ! -f "/usr/local/bin/backup-job.sh" ]; then
echo "Error: Target script /usr/local/bin/backup-job.sh not found." >&2
exit 1
fi
# Idempotently append to the crontab
(crontab -l 2>/dev/null | grep -Fv "/usr/local/bin/backup-job.sh"; echo "$CRON_CMD") | crontab -
echo "Cron job successfully scheduled for 22:00 Monday-Friday." › Setup notes
Save the script to a file named setup-cron.sh, make it executable using chmod +x setup-cron.sh, and run it as a user with appropriate crontab permissions.
const cron = require('node-cron');
const { exec } = require('child_process');
console.log('Initializing scheduler dynamic worker...');
// Schedule the weekday task at 10:00 PM (22:00)
const scheduledTask = cron.schedule('0 22 * * 1-5', () => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] Starting scheduled weekday night processing...`);
exec('/usr/local/bin/process-batch.sh', (error, stdout, stderr) => {
if (error) {
console.error(`[${timestamp}] Execution failed:`, error.message);
return;
}
if (stderr) {
console.warn(`[${timestamp}] Standard Error Output:`, stderr);
}
console.log(`[${timestamp}] Execution output:`, stdout);
});
}, {
scheduled: true,
timezone: "America/New_York"
});
scheduledTask.start(); › Setup notes
Install the node-cron package using npm install node-cron, save this script to scheduler.js, and execute it continuously using a process manager like PM2.
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 execute_nightly_pipeline():
try:
logger.info("Initiating weekday nightly data pipeline run...")
# Insert production database synchronization or backup logic here
logger.info("Pipeline execution completed successfully.")
except Exception as e:
logger.error(f"Pipeline failed with unhandled exception: {str(e)}")
scheduler = BlockingScheduler()
# Add cron trigger for Monday-Friday (1-5) at 22:00 America/New_York
scheduler.add_job(
execute_nightly_pipeline,
'cron',
day_of_week='mon-fri',
hour=22,
minute=0,
timezone='America/New_York'
)
try:
logger.info("Starting APScheduler daemon...")
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped manually.") › Setup notes
Install APScheduler using pip install apscheduler, save the script to pipeline_cron.py, and run it as a persistent background daemon.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
// Load the target execution timezone
loc, err := time.LoadLocation("America/New_York")
if err != nil {
log.Fatalf("Failed to load timezone: %v", err)
}
c := cron.New(cron.WithLocation(loc))
_, err = c.AddFunc("0 22 * * 1-5", func() {
log.Println("Starting weekday nightly system synchronization task...")
// Execute business logic here safely
})
if err != nil {
log.Fatalf("Failed to register cron job schedule: %v", err)
}
c.Start()
log.Println("Scheduler successfully started. Waiting for execution events...")
// Handle graceful shutdown signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Stopping scheduler daemon gracefully...")
c.Stop()
} › Setup notes
Initialize a Go module, run go get github.com/robfig/cron/v3, save the code to main.go, and compile using go build -o cronapp main.go.
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 WeekdayNightlyScheduler {
private static final Logger logger = LoggerFactory.getLogger(WeekdayNightlyScheduler.class);
// Spring Cron format: second, minute, hour, day-of-month, month, day-of-week
// 'MON-FRI' corresponds to standard cron's '1-5'
@Scheduled(cron = "0 0 22 * * MON-FRI", zone = "America/New_York")
public void runWeekdayNightlyJob() {
logger.info("Triggering scheduled weekday nightly maintenance window tasks...");
try {
// Database cleanup, index optimization, or backup tasks go here
logger.info("Maintenance tasks executed successfully.");
} catch (Exception ex) {
logger.error("Error occurred during maintenance window execution", ex);
}
}
} › Setup notes
Ensure @EnableScheduling is added to your primary Spring Boot Application class. Place this class in your project's component-scanned package structure.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekday-nightly-backup
namespace: production
spec:
schedule: "0 22 * * 1-5"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: backup-worker
image: postgres:15-alpine
command:
- /bin/sh
- -c
- "echo 'Starting DB Backup...'; pg_dumpall -U postgres > /mnt/backups/db_$(date +%F).sql && echo 'Backup Complete'"
env:
- name: PGHOST
value: "db-service"
restartPolicy: OnFailure › Setup notes
Save this YAML block to a file named cronjob.yaml and apply it to your Kubernetes cluster using the command kubectl apply -f cronjob.yaml.
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 22 ? * 1-5 *) Systemd Timer
OnCalendarMon..Fri *-*-* 22:00:00
[Unit]
Description=Timer for cron expression: 0 22 * * 1-5
[Timer]
OnCalendar=Mon..Fri *-*-* 22:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How does Daylight Saving Time affect a 10 PM weekday cron job?
If your host OS or execution environment is set to local time (e.g., Eastern Time), the job will shift along with Daylight Saving Time transitions. This means it will always execute at 10:00 PM local time. If your system is set to UTC, the execution time relative to your local time will shift forward or backward by one hour twice a year. To prevent this, configure your scheduler or runner to target a specific timezone instead of falling back to UTC.
Can I use this expression to run jobs on weekends too?
No, this specific expression (`1-5` in the fifth field) restricts execution strictly to Monday through Friday. If you want to include weekends, you must change the fifth field to `0-6` (or `*`), which would schedule the task to run every single night of the week at 10:00 PM.
What happens if a weekday holiday falls on one of these run times?
Standard cron engines do not possess holiday awareness; they will execute the scheduled task on holidays if they fall on a weekday. To prevent executions on corporate holidays, you must write program logic inside your application or wrapper script to check a holiday calendar API or database and gracefully exit early.
How can I prevent overlapping runs if a Friday job takes over 24 hours?
To prevent concurrent execution overlaps, you must implement a locking mechanism. In Kubernetes, you can set `concurrencyPolicy: Forbid`. In custom environments, use file locks via `flock` or distributed locks via Redis or Consul to ensure that if a previous night's job is still active, the new run terminates immediately.
Why is my task running at 5 PM instead of 10 PM?
This is almost always a timezone mismatch. Your system or application daemon is likely running on UTC time, which makes 10:00 PM UTC correspond to 5:00 PM EST or 6:00 PM EDT. To fix this, change the server's system timezone to your local timezone, or use a scheduling library (like APScheduler or Spring) that explicitly supports timezone overrides.
* Explore
Related expressions you might need
Last verified: