Execute Jobs Every Five Minutes | CronBase
*/5 * * * * Every five minutes, continuously throughout the hour, day, and week.
The `*/5 * * * *` cron expression schedules a command to run repeatedly at five-minute intervals, specifically at minutes zero, five, ten, fifteen, and so on, every hour of every day. It is commonly used for high-frequency tasks like API polling, system health monitoring, and queue processing.
- Minute
- */5
- Hour
- *
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 1m 37s
- in 6m 37s
- in 11m 37s
- in 16m 37s
- in 21m 37s
* Tools
Code & Implementations
#!/usr/bin/env bash
# Prevent overlapping executions using flock
LOCKFILE="/var/lock/five_minute_job.lock"
exec 9>"$LOCKFILE"
if ! flock -n 9; then
echo "Error: Another instance of this job is already running." >&2
exit 1
fi
echo "Starting high-frequency task at $(date)"
# Real production workload goes here
# Example: curl -sf https://api.example.com/health || exit 1 › Setup notes
Save this script to /usr/local/bin/five_minute_job.sh, make it executable with chmod +x, and add it to your crontab using: */5 * * * * /usr/local/bin/five_minute_job.sh
const cron = require('node-cron');
let isRunning = false;
// Schedule to run every 5 minutes
cron.schedule('*/5 * * * *', async () => {
if (isRunning) {
console.warn('Execution skipped: Previous task is still running.');
return;
}
isRunning = true;
try {
console.log('Starting execution cycle...');
await performTask();
} catch (error) {
console.error('Task failed:', error);
} finally {
isRunning = false;
}
});
function performTask() {
return new Promise((resolve) => setTimeout(resolve, 5000));
} › Setup notes
Install the node-cron package using 'npm install node-cron' and run this script as a daemon using a process manager like PM2 to ensure continuous execution.
import os
import sys
import fcntl
from datetime import datetime
lock_file_path = "/tmp/python_five_min_job.lock"
lock_file = open(lock_file_path, "w")
try:
# Non-blocking lock acquisition
fcntl.lockf(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print(f"[{datetime.now()}] Job is already running. Exiting.", file=sys.stderr)
sys.exit(0)
def main():
print(f"[{datetime.now()}] Starting periodic job execution...")
# Put your core business logic here
if __name__ == "__main__":
try:
main()
finally:
lock_file.close() › Setup notes
Place this script in your project structure and schedule it via crontab using: */5 * * * * /usr/bin/python3 /path/to/script.py. It uses standard library locks to prevent overlapping runs.
package main
import (
"context"
"log"
"sync/atomic"
"time"
"github.com/robfig/cron/v3"
)
func main() {
c := cron.New()
var running int32
_, err := c.AddFunc("*/5 * * * *", func() {
// Atomic check to prevent concurrent execution overlap
if !atomic.CompareAndSwapInt32(&running, 0, 1) {
log.Println("Previous execution still in progress, skipping run.")
return
}
defer atomic.StoreInt32(&running, 0)
log.Println("Executing scheduled task...")
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
if err := executeTask(ctx); err != nil {
log.Printf("Task failed: %v", err)
}
})
if err != nil {
log.Fatalf("Failed to schedule cron: %v", err)
}
c.Start()
select {} // Keep application running
}
func executeTask(ctx context.Context) error {
// Simulated work
return nil
} › Setup notes
Import 'github.com/robfig/cron/v3' in your Go module. Run the compiled binary as a systemd service to maintain the background scheduler.
package com.example.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
@Component
public class FiveMinuteTaskScheduler {
private static final Logger LOGGER = Logger.getLogger(FiveMinuteTaskScheduler.class.getName());
private final AtomicBoolean isRunning = new AtomicBoolean(false);
// Spring's cron scheduler configuration
@Scheduled(cron = "0 */5 * * * *")
public void executeTask() {
if (!isRunning.compareAndSet(false, true)) {
LOGGER.warning("Previous job execution is still active. Skipping this cycle.");
return;
}
try {
LOGGER.info("Starting five-minute maintenance job...");
runBusinessLogic();
} finally {
isRunning.set(false);
}
}
private void runBusinessLogic() {
// Business logic goes here
}
} › Setup notes
Enable scheduling in your Spring Boot application by adding @EnableScheduling to your main application class, then include this component in your scanned package paths.
apiVersion: batch/v1
kind: CronJob
metadata:
name: five-minute-cleanup-job
namespace: default
spec:
schedule: "*/5 * * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
template:
spec:
containers:
- name: worker
image: busybox:1.36
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- "echo 'Starting task...'; sleep 10; echo 'Task complete.'"
restartPolicy: OnFailure › Setup notes
Apply this manifest using 'kubectl apply -f cronjob.yaml'. Note the use of 'concurrencyPolicy: Forbid' to ensure Kubernetes does not launch overlapping pods if a previous pod hangs.
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 * * * ? *) Systemd Timer
OnCalendar*-*-* *:00/5:00
[Unit]
Description=Timer for cron expression: */5 * * * *
[Timer]
OnCalendar=*-*-* *:00/5:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I prevent overlapping executions if a job takes longer than 5 minutes?
Use a locking mechanism. In Bash, wrap your command with `flock -n /var/lock/myjob.lock`. In application code, implement a distributed lock using Redis (Redlock) or a database-backed state lock to ensure only one instance runs at a time.
Will changing the system timezone affect this 5-minute schedule?
Because this expression runs continuously every five minutes regardless of the hour or day, timezone shifts (such as Daylight Saving Time) will not interrupt the frequency. The job will continue to execute every five minutes, though timestamp logs will reflect the timezone change.
How can I monitor if my 5-minute cron job fails silently?
Implement 'dead man's switch' monitoring (e.g., Healthchecks.io or Opsgenie). Have your script send an HTTP ping to an external service at the end of each successful run. If the service doesn't receive a ping within 6 or 7 minutes, it triggers an alert.
What is the performance impact of running a database query every 5 minutes?
If the query is unindexed or scans large tables, it can degrade database performance and exhaust connection pools. Ensure your queries use indexes, keep connection durations short, use connection pooling, and implement strict read timeouts.
Can I offset this job to run at minutes 2, 7, 12 instead of 0, 5, 10?
Yes, you can shift the execution offset by changing the expression to `2/5 * * * *`. This is highly recommended in shared hosting or microservice environments to avoid resource spikes that occur when multiple jobs align at the top of the 5-minute mark.
* Explore
Related expressions you might need
Last verified: