Run Every Three Minutes Schedule Guide | CronBase
*/3 * * * * Every three minutes
The `*/3 * * * *` cron expression executes a task automatically every three minutes of every hour, every day of the week, and every month of the year. This rapid interval is typically used for continuous monitoring, high-frequency data ingestion, log rotation checks, and health probes in distributed microservices.
- Minute
- */3
- Hour
- *
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 37s
- in 3m 37s
- in 6m 37s
- in 9m 37s
- in 12m 37s
* Tools
Code & Implementations
#!/usr/bin/env bash
# Production Bash script for a 3-minute cron task with locking mechanism
set -euo pipefail
LOCKFILE="/var/lock/my_three_minute_task.lock"
TIMEOUT_SECS=170 # Slightly less than 3 minutes to prevent overlap
# Ensure single instance execution using flock
exec 9>"$LOCKFILE"
if ! flock -n 9; then
echo "[ERROR] Another instance of the task is still running. Exiting to prevent overlap." >&2
exit 1
fi
echo "[INFO] Starting 3-minute cron execution at $(date -u)"
# Simulate production workload with timeout protection
timeout "$TIMEOUT_SECS" curl -sSf https://api.internal/health-check || {
echo "[ERROR] Task failed or timed out" >&2
exit 1
}
echo "[INFO] Task completed successfully" › Setup notes
Save the script to /usr/local/bin/three_min_job.sh, make it executable using chmod +x, and configure it inside your crontab using: */3 * * * * /usr/local/bin/three_min_job.sh >> /var/log/three_min_job.log 2>&1
const cron = require('node-cron');
const axios = require('axios');
let isTaskRunning = false;
// Schedule task for every 3 minutes: */3 * * * *
cron.schedule('*/3 * * * *', async () => {
if (isTaskRunning) {
console.warn('[WARN] Previous task execution is still active. Skipping run to prevent race conditions.');
return;
}
isTaskRunning = true;
console.log(`[INFO] Executing high-frequency task at ${new Date().toISOString()}`);
try {
const response = await axios.get('https://api.example.com/v1/metrics', { timeout: 150000 });
console.log(`[INFO] Metrics collected successfully. Status: ${response.status}`);
} catch (error) {
console.error('[ERROR] Failed to execute 3-minute cron task:', error.message);
} finally {
isTaskRunning = false;
}
}); › Setup notes
Install dependencies using 'npm install node-cron axios'. Run this long-running daemon process using PM2 or a systemd service to ensure continuous execution.
import logging
import sys
import requests
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
def fetch_queue_status():
logger.info("Starting queue status check...")
try:
response = requests.get("https://api.internal/queue/status", timeout=120)
response.raise_for_status()
logger.info(f"Queue check successful: {response.json()}")
except requests.exceptions.RequestException as e:
logger.error(f"Network error during queue check: {e}")
except Exception as e:
logger.error(f"Unexpected error: {e}")
if __name__ == "__main__":
scheduler = BlockingScheduler()
# Adding a job for every 3 minutes using standard cron syntax
scheduler.add_job(
fetch_queue_status,
'cron',
minute='*/3',
id='queue_status_job',
coalesce=True,
max_instances=1
)
logger.info("Starting scheduler for every 3 minutes...")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped cleanly.") › Setup notes
Install the required modules using 'pip install apscheduler requests' and run the script as a background worker process in your server environment.
package main
import (
"context"
"log"
"net/http"
"sync"
"time"
"github.com/robfig/cron/v3"
)
type SafeRunner struct {
mu sync.Mutex
active bool
}
func (r *SafeRunner) Run() {
r.mu.Lock()
if r.active {
log.Println("[WARN] Task is already running; skipping execution")
r.mu.Unlock()
return
}
r.active = true
r.mu.Unlock()
defer func() {
r.mu.Lock()
r.active = false
r.mu.Unlock()
}()
log.Println("[INFO] Starting 3-minute task execution...")
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", "https://api.internal/v1/jobs", nil)
if err != nil {
log.Printf("[ERROR] Failed to create request: %v", err)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("[ERROR] Request failed: %v", err)
return
}
defer resp.Body.Close()
log.Printf("[INFO] Execution finished with status code %d", resp.StatusCode)
}
func main() {
c := cron.New()
runner := &SafeRunner{}
_, err := c.AddJob("*/3 * * * *", runner)
if err != nil {
log.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
select {} // Keep running
} › Setup notes
Initialize your project with 'go mod init', fetch the cron package using 'go get github.com/robfig/cron/v3', and compile the code using 'go build'.
package com.example.cron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.time.Duration;
@Component
public class HighFrequencyTaskScheduler {
private static final Logger logger = LoggerFactory.getLogger(HighFrequencyTaskScheduler.class);
private final HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
// Cron expression for every 3 minutes: */3 * * * *
@Scheduled(cron = "0 */3 * * * *")
public void executeTask() {
logger.info("Executing 3-minute health sync job...");
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.internal/health"))
.timeout(Duration.ofSeconds(150))
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
logger.info("Health check response code: {}", response.statusCode());
} catch (InterruptedException e) {
logger.error("Execution interrupted", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
logger.error("Failed to complete 3-minute scheduled task", e);
}
}
} › Setup notes
Add '@EnableScheduling' to your main Spring Boot configuration class, place this component in a scanned package, and configure your thread pool to handle scheduled tasks appropriately.
apiVersion: batch/v1
kind: CronJob
metadata:
name: high-frequency-cleanup
namespace: production
spec:
schedule: "*/3 * * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
startingDeadlineSeconds: 60
jobTemplate:
spec:
template:
spec:
containers:
- name: worker
image: internal-registry.io/ops/cleanup-worker:v1.2.0
imagePullPolicy: IfNotPresent
resources:
limits:
cpu: "200m"
memory: "256Mi"
requests:
cpu: "100m"
memory: "128Mi"
restartPolicy: OnFailure › Setup notes
Deploy this manifest to your cluster using 'kubectl apply -f cronjob.yaml'. Monitor executions using 'kubectl get cronjob' and view pod logs to verify correct execution timing.
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(*/3 * * * ? *) Systemd Timer
OnCalendar*-*-* *:00/3:00
[Unit]
Description=Timer for cron expression: */3 * * * *
[Timer]
OnCalendar=*-*-* *:00/3:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
What happens if a task takes longer than 3 minutes to run?
If a task exceeds the 3-minute window, a new execution will start concurrently unless concurrency controls are set. This can lead to race conditions, CPU spikes, and database connection pool exhaustion. Implement distributed locks or concurrency policies like Kubernetes 'Forbid' to prevent this.
How can I prevent overlapping runs on this fast schedule?
Prevent overlapping by using flock in Bash scripts, setting concurrencyPolicy: Forbid in Kubernetes CronJobs, or utilizing memory/mutex locks in application code. For distributed setups, implement a lock using Redis or a database table to ensure only one instance executes at a time.
Is this high-frequency schedule safe for database transactions?
Generally, no. Running database-heavy operations every 3 minutes can lead to lock contention, transaction timeouts, and high CPU utilization. If database writes are necessary, keep them highly optimized, use indexed fields, batch the transactions, and ensure connections are released immediately.
How does timezone configuration affect this 3-minute cron?
Because the job runs continuously every 3 minutes, local timezone shifts (like Daylight Saving Time) do not affect the frequency of execution; it will still execute every 3 minutes. However, your logging and audit timestamps may shift, so setting the system timezone to UTC is highly recommended.
Can I use standard cron for sub-minute executions?
No, standard cron dialects only support a minimum resolution of one minute. If you require sub-minute execution (e.g., every 30 seconds), you must use a daemonized loop, a specialized task scheduler like Celery, or a continuous service runner rather than cron.
* Explore
Related expressions you might need
Last verified: