Every 5 Minutes on Weekdays Cron Schedule | CronBase
*/5 * * * 1-5 Every five minutes on weekdays
This cron expression schedules a task to run every five minutes, but only on weekdays from Monday through Friday. It is ideal for continuous monitoring, high-frequency data ingestion, and API polling during standard business days, ensuring operations pause automatically over the weekend to reduce unnecessary cloud infrastructure costs.
- Minute
- */5
- Hour
- *
- Day of Month
- *
- Month
- *
- Day of Week
- 1-5
Next 5 Runs
- in 1d 3h
- in 1d 3h
- in 1d 3h
- in 1d 3h
- in 1d 3h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Production Bash execution wrapper for standard cron
# Cron entry: */5 * * * 1-5 /usr/local/bin/weekday_sync.sh >> /var/log/cron_sync.log 2>&1
set -euo pipefail
LOCKFILE="/var/run/weekday_sync.lock"
TIMEOUT_SECONDS=280 # Exit before the next 5-minute invocation
# Ensure only one instance runs at a time using flock
exec 9>>"$LOCKFILE"
if ! flock -n 9; then
echo "[$(date -u '+\%Y-\%m-\%dT\%H:\%M:\%SZ')] Warning: Previous execution is still running. Exiting to prevent overlap."
exit 0
fi
# Execute actual payload with a timeout
echo "[$(date -u '+\%Y-\%m-\%dT\%H:\%M:\%SZ')] Starting weekday synchronization..."
timeout "$TIMEOUT_SECONDS" curl -fsS --retry 3 https://api.internal.service/v1/sync || {
echo "[$(date -u '+\%Y-\%m-\%dT\%H:\%M:\%SZ')] Error: Sync failed or timed out."
exit 1
}
echo "[$(date -u '+\%Y-\%m-\%dT\%H:\%M:\%SZ')] Sync completed successfully." › Setup notes
Save this script as /usr/local/bin/weekday_sync.sh, make it executable with chmod +x, and add */5 * * * 1-5 /usr/local/bin/weekday_sync.sh >> /var/log/cron_sync.log 2>&1 to your system crontab.
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule: */5 * * * 1-5 (Every 5 minutes, Monday through Friday)
const cronExpression = '*/5 * * * 1-5';
let isRunning = false;
console.log(`Scheduler initialized. Active pattern: ${cronExpression}`);
const task = cron.schedule(cronExpression, async () => {
if (isRunning) {
console.warn(`[${new Date().toISOString()}] Task overlap detected; skipping execution.`);
return;
}
isRunning = true;
console.log(`[${new Date().toISOString()}] Executing weekday queue processing...`);
try {
await new Promise((resolve, reject) => {
// Simulate database queue processing
setTimeout(() => {
const success = true;
if (success) resolve();
else reject(new Error('Database query failure'));
}, 5000);
});
console.log(`[${new Date().toISOString()}] Queue processing completed.`);
} catch (error) {
console.error(`[${new Date().toISOString()}] Error during execution:`, error.message);
} finally {
isRunning = false;
}
}, {
scheduled: true,
timezone: "UTC"
}); › Setup notes
Install node-cron using npm install node-cron, then run this script using node scheduler.js in a PM2 or systemd process supervisor.
import time
import logging
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_ingestion_job():
logger.info("Starting high-frequency weekday ingestion...")
try:
# Simulate data pipeline execution
time.sleep(10)
logger.info("Ingestion completed successfully.")
except Exception as e:
logger.error(f"Ingestion failed: {str(e)}")
if __name__ == "__main__":
scheduler = BlockingScheduler()
# */5 * * * 1-5 maps to: minute='*/5', hour='*', day='*', month='*', day_of_week='mon-fri'
trigger = CronTrigger(minute='*/5', day_of_week='mon-fri', timezone='UTC')
scheduler.add_job(
execute_ingestion_job,
trigger=trigger,
id='weekday_ingestion_job',
max_instances=1, # Prevent concurrent execution
coalesce=True
)
logger.info("Starting APScheduler daemon for weekday interval...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped cleanly.") › Setup notes
Install APScheduler using pip install apscheduler and execute the script with python scheduler.py to run the daemon in UTC.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "CRON: ", log.LstdFlags|log.Lshortfile)
// Use UTC as standard practice for cloud native crons
c := cron.New(cron.WithLocation(time.UTC))
// */5 * * * 1-5 standard schedule translated to robfig/cron
_, err := c.AddFunc("*/5 * * * 1-5", func() {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
logger.Println("Running scheduled weekday healthcheck...")
if err := runHealthcheck(ctx); err != nil {
logger.Printf("Healthcheck failed: %v\n", err)
} else {
logger.Println("Healthcheck finished successfully.")
}
})
if err != nil {
logger.Fatalf("Error scheduling job: %v", err)
}
c.Start()
logger.Println("Cron scheduler started successfully")
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down cron scheduler...")
c.Stop()
}
func runHealthcheck(ctx context.Context) error {
select {
case <-time.After(2 * time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
} › Setup notes
Initialize your Go module, run go get github.com/robfig/cron/v3, and run this program using go run 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 WeekdayDataSyncScheduler {
private static final Logger logger = LoggerFactory.getLogger(WeekdayDataSyncScheduler.class);
private static boolean isJobRunning = false;
// Spring Cron format: second, minute, hour, day of month, month, day(s) of week
// "0 */5 * * * MON-FRI" evaluates to every 5 minutes on weekdays
@Scheduled(cron = "0 */5 * * * MON-FRI", zone = "UTC")
public synchronized void performWeekdaySync() {
if (isJobRunning) {
logger.warn("Previous sync task is still running. Skipping execution.");
return;
}
isJobRunning = true;
logger.info("Starting sync operation...");
try {
// Perform actual database or API processing
Thread.sleep(15000);
logger.info("Sync completed successfully.");
} catch (InterruptedException e) {
logger.error("Sync job was interrupted", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
logger.error("Error during sync processing", e);
} finally {
isJobRunning = false;
}
}
} › Setup notes
Ensure your Spring Boot application class is annotated with @EnableScheduling. Add this component to your codebase to trigger automatic execution.
apiVersion: batch/v1
kind: CronJob
metadata:
name: weekday-batch-processor
namespace: default
spec:
schedule: "*/5 * * * 1-5"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 100
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
activeDeadlineSeconds: 280
template:
spec:
containers:
- name: processor
image: python:3.9-slim
command:
- python
- -c
- |
import sys
import urllib.request
try:
print("Processing weekday metrics...")
with urllib.request.urlopen("https://api.internal.service/v1/heartbeat", timeout=10) as response:
print(f"Status: {response.getcode()}")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "300m"
memory: "256Mi"
restartPolicy: OnFailure › Setup notes
Apply this configuration to your Kubernetes cluster using kubectl apply -f cronjob.yaml. The concurrencyPolicy: Forbid prevents concurrent pods from executing if a previous job gets stuck.
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(*/5 * ? * 1-5 *) Systemd Timer
OnCalendarMon..Fri *-*-* *:00/5:00
[Unit]
Description=Timer for cron expression: */5 * * * 1-5
[Timer]
OnCalendar=Mon..Fri *-*-* *:00/5:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I prevent overlapping executions if a run takes longer than 5 minutes?
You should implement a locking mechanism such as Redis-based distributed locks, database-level flags, or file-based locks (`flock` in Linux). In Kubernetes, configure `concurrencyPolicy: Forbid` to automatically skip execution if the previous pod is still active.
What happens to the schedule during daylight saving time (DST) changes?
If your server timezone is set to a region that observes DST, the execution times will shift relative to UTC. To maintain a consistent 5-minute interval without interruption or double-execution during the fallback hour, it is highly recommended to run your cron daemon on UTC.
How can I handle the massive backlog accumulated over the weekend on Monday morning?
Design your worker to process data in small, deterministic batches rather than attempting to ingest all weekend data in a single run. Use cursor-based pagination and implement rate-limiting or backpressure to protect downstream APIs and databases from being overwhelmed.
Why does my weekday cron start running on Sunday afternoon in my local timezone?
This occurs because your cron daemon is running in UTC. Monday 00:00 UTC corresponds to Sunday evening in Western time zones (e.g., 7:00 PM EST). To fix this, you must either configure your cron environment to use your local timezone or shift the hour and day-of-week fields to compensate.
Can I exclude specific holidays that fall on weekdays from this schedule?
Standard cron syntax does not support holiday calendars. To bypass holidays, you must implement application-level logic at the beginning of your script to check the current date against a holiday list (e.g., using a library or database table) and exit early if a match is found.
* Explore
Related expressions you might need
Last verified: