Automate Tasks Every 20 Minutes | CronBase
*/20 * * * * Every twenty minutes, recurring continuously throughout the day and night.
The `*/20 * * * *` cron expression schedules a task to run every twenty minutes, specifically at the zero, twenty, and forty-minute marks of every hour, every day. It is commonly used for recurring maintenance tasks, batch data pipelines, and API synchronization jobs that require frequent updates without overloading systems.
- Minute
- */20
- Hour
- *
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 7m 32s
- in 27m 32s
- in 47m 32s
- in 1h 7m
- in 1h 27m
* Tools
Code & Implementations
#!/usr/bin/env bash
set -euo pipefail
# Use flock to prevent overlapping executions every 20 minutes
LOCKFILE="/var/lock/my-20min-job.lock"
exec 9>"$LOCKFILE"
if ! flock -n 9; then
echo "Error: Another instance of the job is already running." >&2
exit 1
fi
echo "Starting 20-minute maintenance task..."
# Place actual operational logic here (e.g., sync scripts, cleanup)
/usr/local/bin/sync-api-data.sh
echo "Task completed successfully." › Setup notes
Save this script to /usr/local/bin/sync-job.sh, make it executable with chmod +x, and add '*/20 * * * * /usr/local/bin/sync-job.sh' to your system crontab.
const cron = require('node-cron');
// Schedule task to run every 20 minutes (at :00, :20, and :40)
cron.schedule('*/20 * * * *', async () => {
console.log(`[${new Date().toISOString()}] Starting scheduled sync...`);
try {
// Simulate operational work or call external service
await performSync();
console.log('Sync completed successfully.');
} catch (error) {
console.error('Execution failed:', error);
}
});
async function performSync() {
return new Promise((resolve) => setTimeout(resolve, 5000));
} › Setup notes
Install node-cron using 'npm install node-cron' and run this script within a long-running PM2 or Node daemon process.
import datetime
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("cron_job")
def execute_task():
logger.info(f"Job started at {datetime.datetime.now()}")
try:
# Perform the 20-minute interval business logic
pass
except Exception as e:
logger.error(f"Execution failed: {e}")
if __name__ == "__main__":
scheduler = BlockingScheduler()
# Trigger job every 20 minutes
scheduler.add_job(execute_task, 'cron', minute='*/20')
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass › Setup notes
Install the required package via 'pip install apscheduler' and run the script as a background service.
package main
import (
"context"
"log"
"time"
"github.com/robfig/cron/v3"
)
func main() {
c := cron.New()
_, err := c.AddFunc("*/20 * * * *", func() {
log.Println("Starting 20-minute batch execution...")
// Implement 18-minute timeout to prevent overlapping runs
ctx, cancel := context.WithTimeout(context.Background(), 18*time.Minute)
defer cancel()
select {
case <-time.After(5 * time.Second):
log.Println("Batch execution complete.")
case <-ctx.Done():
log.Println("Job cancelled or timed out.")
}
})
if err != nil {
log.Fatalf("Failed to schedule cron: %v", err)
}
c.Start()
select {}
} › Setup notes
Initialize your module, run 'go get github.com/robfig/cron/v3', and build the binary for production execution.
package com.cronbase.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.logging.Logger;
@Component
public class TwentyMinuteScheduler {
private static final Logger LOGGER = Logger.getLogger(TwentyMinuteScheduler.class.getName());
// Runs every 20 minutes (at :00, :20, and :40 past the hour)
@Scheduled(cron = "0 */20 * * * *")
public void executeTask() {
LOGGER.info("Starting scheduled task at: " + LocalDateTime.now());
try {
performMaintenance();
} catch (Exception e) {
LOGGER.severe("Task execution encountered an error: " + e.getMessage());
}
}
private void performMaintenance() {
// Actual business logic execution
}
} › Setup notes
Ensure @EnableScheduling is added to your Spring Boot main application class to activate scheduled tasks.
apiVersion: batch/v1
kind: CronJob
metadata:
name: twenty-minute-cleanup
namespace: default
spec:
schedule: "*/20 * * * *"
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 20-minute clean up task'; sleep 30; echo 'Task complete'"
restartPolicy: OnFailure › Setup notes
Apply this configuration using 'kubectl apply -f cronjob.yaml' to schedule the containerized task in your cluster.
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(*/20 * * * ? *) Systemd Timer
OnCalendar*-*-* *:00/20:00
[Unit]
Description=Timer for cron expression: */20 * * * *
[Timer]
OnCalendar=*-*-* *:00/20:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
What exact minutes does this cron expression trigger on?
This cron expression triggers exactly at 0, 20, and 40 minutes past every hour (e.g., 12:00, 12:20, 12:40).
How can I prevent executions from overlapping if a task takes longer than 20 minutes?
Use file locks (`flock` in Linux), distributed lock managers like Redis (Redlock), or Kubernetes concurrency policy set to `Forbid` to ensure only one instance runs at a time.
Does this cron schedule adapt automatically to Daylight Saving Time (DST) changes?
Standard cron runs based on the host system's timezone. During DST shifts, the 20-minute interval remains consistent, but the absolute hour boundary may shift by one hour.
How does this schedule compare to running a task every 15 minutes?
A 20-minute interval reduces execution frequency from 96 times a day to 72 times a day, saving system resources and downstream API rate limits while maintaining a high frequency.
Can I run this schedule only during specific business hours?
Yes, you can restrict the hour field. For example, `*/20 9-17 * * *` will run the task every 20 minutes only between 9:00 AM and 5:59 PM.
* Explore
Related expressions you might need
Last verified: