Execute Jobs Every Two Minutes Reliably | CronBase
*/2 * * * * Every two minutes, continuously throughout every day.
The `*/2 * * * *` cron expression schedules a job to execute every two minutes, continuously, every single day. It is a high-frequency interval ideal for near-real-time operations, including processing queue messages, polling external APIs, and executing lightweight system health checks or monitoring agents.
- Minute
- */2
- Hour
- *
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 47s
- in 2m 47s
- in 4m 47s
- in 6m 47s
- in 8m 47s
* Tools
Code & Implementations
#!/bin/bash
# Production-ready Bash script with lock protection to prevent overlap
LOCKFILE="/var/lock/my_two_minute_job.lock"
# Acquire an exclusive lock without blocking
exec 200>"$LOCKFILE"
flock -n 200 || {
echo "[$(date)] Warning: Job is already running, skipping execution to avoid overlap."
exit 1
}
echo "[$(date)] Initiating high-frequency polling task..."
timeout 110s curl -s -f https://api.internal/v1/poll-tasks || {
echo "[$(date)] Error: API request failed or timed out."
exit 1
}
echo "[$(date)] Task completed successfully." › Setup notes
Place this script in /usr/local/bin/poll-job.sh, make it executable, and add '*/2 * * * * /usr/local/bin/poll-job.sh >> /var/log/poll-job.log 2>&1' to your system crontab.
const cron = require('node-cron');
const axios = require('axios');
let isRunning = false;
// Schedule task to run every two minutes
cron.schedule('*/2 * * * *', async () => {
if (isRunning) {
console.warn('[Cron] Previous job is still running; skipping execution.');
return;
}
isRunning = true;
console.log('[Cron] Starting execution...');
try {
const response = await axios.get('https://api.internal/v1/health', { timeout: 10000 });
console.log(`[Cron] System health status: ${response.data.status}`);
} catch (error) {
console.error('[Cron] Execution failed:', error.message);
} finally {
isRunning = false;
}
}); › Setup notes
Install dependencies using 'npm install node-cron axios'. Run this script using a process manager like PM2 to guarantee uptime.
import time
import requests
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
@scheduler.scheduled_job('cron', minute='*/2')
def execute_task():
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Executing database cleanup... ")
try:
# Set a strict timeout to prevent hanging connections
response = requests.post("https://api.internal/v1/cleanup", timeout=90)
response.raise_for_status()
print("Database cleanup completed successfully.")
except requests.exceptions.RequestException as e:
print(f"Cleanup failed: {e}")
if __name__ == '__main__':
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass › Setup notes
Install the required packages with 'pip install apscheduler requests'. Run the script directly to start the daemonized blocking scheduler.
package main
import (
"context"
"log"
"net/http"
"time"
"github.com/robfig/cron/v3"
)
func main() {
c := cron.New()
_, err := c.AddFunc("*/2 * * * *", func() {
log.Println("Starting two-minute queue processing...")
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "POST", "https://api.internal/v1/queue", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("Queue processing failed: %v", err)
return
}
defer resp.Body.Close()
log.Printf("Queue processed with status: %s", resp.Status)
})
if err != nil {
log.Fatalf("Error scheduling cron job: %v", err)
}
c.Start()
select {} // Block main thread to keep service running
} › Setup notes
Initialize your Go module, run 'go get github.com/robfig/cron/v3', and start the service binary.
package com.example.cron;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class HighFrequencyTask {
private static final Logger logger = LoggerFactory.getLogger(HighFrequencyTask.class);
private boolean isProcessing = false;
@Scheduled(cron = "*/2 * * * * *", zone = "UTC")
public synchronized void executeTask() {
if (isProcessing) {
logger.warn("Task execution skipped: previous instance is still running.");
return;
}
isProcessing = true;
logger.info("Starting high-frequency data pipeline sync...");
try {
// Simulate fast pipeline operations
Thread.sleep(5000);
logger.info("Data pipeline sync completed.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Task interrupted: ", e);
} finally {
isProcessing = false;
}
}
} › Setup notes
Ensure '@EnableScheduling' is added to your main Spring Boot Application class. The class must be defined as a Spring Bean (e.g., '@Component').
apiVersion: batch/v1
kind: CronJob
metadata:
name: fast-polling-cronjob
namespace: default
spec:
schedule: "*/2 * * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 1
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
containers:
- name: poller
image: curlimages/curl:latest
command:
- /bin/sh
- -c
- "curl -m 100 -f https://api.internal/v1/heartbeat"
restartPolicy: OnFailure › Setup notes
Apply this manifest using 'kubectl apply -f cronjob.yaml'. Setting 'concurrencyPolicy: Forbid' is critical to prevent overlapping Pods.
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(*/2 * * * ? *) Systemd Timer
OnCalendar*-*-* *:00/2:00
[Unit]
Description=Timer for cron expression: */2 * * * *
[Timer]
OnCalendar=*-*-* *:00/2:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I prevent overlapping executions if a job takes longer than two minutes?
Use a locking mechanism like flock in Bash, or set concurrencyPolicy: Forbid in Kubernetes. For application-level jobs, use Redis-based distributed locks (Redlock) or database flags to ensure only one instance runs at a time.
Will this high-frequency schedule impact my log storage and monitoring costs?
Yes, executing every two minutes generates 720 executions per day. Verbose logging will quickly inflate storage costs. Implement structured metrics (e.g., Prometheus) for success tracking and restrict stdout logs to warnings, errors, or execution summaries.
Is standard cron guaranteed to run precisely every 120 seconds?
Standard system cron daemons check schedules at the minute boundary. While it triggers every two minutes, minor scheduling latency (milliseconds to a few seconds) can occur depending on system load. If sub-second precision is required, use a dedicated queue worker or systemd timer.
How should I handle external API rate limits with a two-minute schedule?
Implement exponential backoff with jitter within your application logic. If an API returns a 429 Too Many Requests status, the job should fail gracefully or pause execution, alerting your monitoring system before retrying on the next scheduled run.
Can I run this schedule on a specific timezone instead of UTC?
Standard system cron runs on the host machine's timezone (usually UTC in cloud environments). If your cron daemon (like modern systemd or Kubernetes 1.27+) supports timezone fields, you can specify it, but keeping the system clock on UTC is the best practice to avoid daylight saving transitions.
* Explore
Related expressions you might need
Last verified: