Schedule Tasks Every Six Hours | CronBase
0 0,6,12,18 * * * Every six hours at midnight, morning, noon, and evening.
This standard cron expression schedules a task to run four times a day, precisely at the start of the hour every six hours. It executes at midnight, morning, midday, and evening. This interval is commonly used for secondary backups, synchronizing external APIs, and processing data pipelines.
- Minute
- 0
- Hour
- 0,6,12,18
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 3h 18m
- in 9h 18m
- in 15h 18m
- in 21h 18m
- in 1d 3h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Production Bash script for 6-hour cron task
# Uses flock to prevent overlapping runs
set -euo pipefail
LOCKFILE="/var/lock/six_hour_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 "[$(date -u)] Starting six-hour maintenance task..."
# Add your actual production payload here
# Example: /usr/local/bin/backup-db.sh
echo "[$(date -u)] Maintenance task completed successfully." › Setup notes
Place this script in /usr/local/bin/six-hour-job.sh, make it executable, and add 0 0,6,12,18 * * * /usr/local/bin/six-hour-job.sh to your system crontab.
const cron = require('node-cron');
// Schedule task to run at 00:00, 06:00, 12:00, and 18:00
cron.schedule('0 0,6,12,18 * * *', async () => {
console.log(`[${new Date().toISOString()}] Starting scheduled job...`);
try {
await runMaintenanceTask();
console.log('Job finished successfully.');
} catch (error) {
console.error('Job failed with error:', error);
}
}, {
scheduled: true,
timezone: "UTC"
});
async function runMaintenanceTask() {
// Real-world production logic here
} › Setup notes
Install node-cron using npm install node-cron, then run this script within a long-running Node.js process managed by PM2 or Docker.
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
scheduler = BlockingScheduler(timezone="UTC")
@scheduler.scheduled_job('cron', hour='0,6,12,18', minute=0)
def run_six_hour_job():
logger.info("Starting six-hour scheduled pipeline execution")
try:
# Production payload goes here
pass
except Exception as e:
logger.error(f"Execution failed: {str(e)}")
if __name__ == "__main__":
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass › Setup notes
Install APScheduler using pip install apscheduler and run this Python script as a background daemon or systemd service.
package main
import (
"fmt"
"log"
"time"
"github.com/robfig/cron/v3"
)
func main() {
// Use UTC to avoid DST issues
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 0,6,12,18 * * *", func() {
log.Println("Starting 6-hour database synchronization...")
if err := performSync(); err != nil {
log.Printf("Sync failed: %v", err)
}
})
if err != nil {
log.Fatalf("Error scheduling cron job: %v", err)
}
c.Start()
select {} // Keep application running
}
func performSync() error {
return nil
} › Setup notes
Run go get github.com/robfig/cron/v3 to install the cron package, compile the application, and run the 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 SixHourScheduler {
private static final Logger logger = LoggerFactory.getLogger(SixHourScheduler.class);
// Runs at 00:00, 06:00, 12:00, and 18:00 UTC
@Scheduled(cron = "0 0 0,6,12,18 * * *", zone = "UTC")
public void executeTask() {
logger.info("Initiating scheduled six-hour data processing task");
try {
processBatchData();
} catch (Exception e) {
logger.error("Error during scheduled task execution", e);
}
}
private void processBatchData() {
// Production-ready business logic here
}
} › Setup notes
Ensure @EnableScheduling is added to your main Spring Boot configuration class, then place this component class in your project.
apiVersion: batch/v1
kind: CronJob
metadata:
name: six-hour-maintenance-job
namespace: default
spec:
schedule: "0 0,6,12,18 * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: worker
image: busybox:1.35
command:
- /bin/sh
- -c
- "echo 'Starting maintenance payload'; sleep 30; echo 'Finished'"
restartPolicy: OnFailure › Setup notes
Apply this configuration file to your cluster using kubectl apply -f cronjob.yaml. The concurrencyPolicy: Forbid ensures jobs do not overlap.
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(0 0,6,12,18 * * ? *) Systemd Timer
OnCalendar*-*-* 00,06,12,18:00:00
[Unit]
Description=Timer for cron expression: 0 0,6,12,18 * * *
[Timer]
OnCalendar=*-*-* 00,06,12,18:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I prevent overlapping executions if a job takes longer than six hours?
You should implement a distributed locking mechanism using Redis or database-backed locks. In Bash, you can use the `flock` utility to prevent a new instance from starting if the previous execution is still running.
What happens to this schedule during Daylight Saving Time (DST) changes?
If your system timezone is set to a local time that observes DST, the 2:00 AM transition can cause the 6:00 AM execution to run early, late, or be skipped. Running your system clock and cron daemon in UTC completely eliminates this risk.
Can I stagger this schedule to avoid peak hour traffic?
Yes, you can shift the execution to a different minute or hour offset. For example, changing the expression to `15 1,7,13,19 * * *` shifts the execution by one hour and fifteen minutes, avoiding resource contention on the hour.
How can I monitor if a six-hour job failed to run?
Implement dead man's snitches or heartbeat monitoring (such as Healthchecks.io or Opsgenie). These services alert your team if they do not receive a ping within a specified window (e.g., six hours and ten minutes).
Is this schedule suitable for high-frequency database backups?
It is ideal for staging or non-critical production databases. However, for critical production databases with high transaction volumes, a six-hour interval may risk losing too much data; a combination of daily full backups and hourly transaction log shipping is preferred.
* Explore
Related expressions you might need
Last verified: