Run Recurring Jobs Every Four Hours | CronBase
0 */4 * * * Every four hours at the top of the hour.
The `0 */4 * * *` cron expression schedules a task to execute every four hours at the top of the hour. Specifically, the job runs at midnight, 4:00 AM, 8:00 AM, 12:00 PM, 4:00 PM, and 8:00 PM daily, making it ideal for semi-frequent maintenance tasks and system synchronization.
- Minute
- 0
- Hour
- */4
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 3h 23m
- in 7h 23m
- in 11h 23m
- in 15h 23m
- in 19h 23m
* Tools
Code & Implementations
#!/usr/bin/env bash
# Production Bash script for 4-hour cron execution
set -euo pipefail
LOG_FILE="/var/log/my_app_four_hour_job.log"
exec >> "$LOG_FILE" 2>&1
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Starting 4-hour maintenance task..."
LOCK_FILE="/var/run/my_app_four_hour_job.lock"
exec 200>"$LOCK_FILE"
if ! flock -n 200; then
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] ERROR: Another instance is already running." >&2
exit 1
fi
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Running database maintenance..."
# Workload logic goes here
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Task completed successfully." › Setup notes
Save this script to /usr/local/bin/four-hour-job.sh, make it executable with 'chmod +x', and add the entry '0 */4 * * * /usr/local/bin/four-hour-job.sh' to your crontab.
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule task to run every 4 hours (0 */4 * * *)
cron.schedule('0 */4 * * *', () => {
console.log(`[${new Date().toISOString()}] Starting scheduled 4-hour job...`);
try {
performMaintenance().catch(err => {
console.error('Task execution failed:', err);
});
} catch (error) {
console.error('Failed to trigger task:', error);
}
});
async function performMaintenance() {
// Simulated production workload
return new Promise((resolve) => setTimeout(resolve, 5000));
} › Setup notes
Install 'node-cron' using 'npm install node-cron' and run this script as a long-running background process using a process manager like PM2.
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
def run_four_hour_job():
logger.info("Starting scheduled 4-hour maintenance job...")
try:
# Place actual production logic here
pass
except Exception as e:
logger.error(f"Job failed with error: {e}", exc_info=True)
if __name__ == "__main__":
scheduler = BlockingScheduler()
scheduler.add_job(run_four_hour_job, 'cron', hour='*/4', minute=0)
logger.info("Scheduler started. Running every 4 hours.")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped.") › Setup notes
Install the required dependency using 'pip install apscheduler' and execute the Python file in your application directory.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "[4-Hour-Job] ", log.LstdFlags|log.Lshortfile)
c := cron.New()
_, err := c.AddFunc("0 */4 * * *", func() {
logger.Println("Executing scheduled 4-hour maintenance...")
if err := executeWorkload(); err != nil {
logger.Printf("Error during execution: %v\n", err)
}
})
if err != nil {
logger.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
logger.Println("Cron scheduler started successfully")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down scheduler...")
c.Stop()
}
func executeWorkload() error {
return nil
} › Setup notes
Initialize your Go module, run 'go get github.com/robfig/cron/v3', compile the program, and run the binary in your production container.
package com.example.cron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class FourHourMaintenanceJob {
private static final Logger logger = LoggerFactory.getLogger(FourHourMaintenanceJob.class);
// Spring cron expression uses 6 fields (second, minute, hour, day, month, day-of-week)
@Scheduled(cron = "0 0 */4 * * *")
public void runMaintenanceTask() {
logger.info("Starting scheduled 4-hour maintenance task...");
try {
executeWorkload();
logger.info("Maintenance task completed successfully.");
} catch (Exception e) {
logger.error("Error executing maintenance task", e);
}
}
private void executeWorkload() {
// Production workload logic goes here
}
} › Setup notes
Ensure '@EnableScheduling' is added to your main Spring Boot Application configuration class to activate scheduled tasks.
apiVersion: batch/v1
kind: CronJob
metadata:
name: four-hour-maintenance-job
namespace: default
spec:
schedule: "0 */4 * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
template:
spec:
containers:
- name: worker
image: busybox:1.35
command:
- /bin/sh
- -c
- echo "Starting 4-hour maintenance task..."; sleep 30; echo "Task completed."
restartPolicy: OnFailure › Setup notes
Save this manifest as 'cronjob.yaml' and apply it to your cluster using 'kubectl apply -f cronjob.yaml'.
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(0 */4 * * ? *) Systemd Timer
OnCalendar*-*-* 00/4:00:00
[Unit]
Description=Timer for cron expression: 0 */4 * * *
[Timer]
OnCalendar=*-*-* 00/4:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
At what exact times of the day does this cron schedule execute?
The schedule executes exactly six times a day at the top of the hour: 00:00, 04:00, 08:00, 12:00, 16:00, and 20:00. This is based on the system timezone unless specified otherwise.
How does Daylight Saving Time affect this 4-hour schedule?
If your system runs on local time, DST shifts can cause the 02:00 to 03:00 transition to skip or repeat an execution. To avoid this, configure your servers to use UTC timezone.
What happens if a job takes longer than 4 hours to complete?
Standard cron will launch a new process even if the previous one is still running. You must use locking mechanisms like flock (Bash) or Redlock (Redis) to prevent overlapping executions.
How can I add a 15-minute offset to this schedule?
You can modify the minute field from 0 to 15, resulting in '15 */4 * * *'. This helps avoid resource spikes at the exact top of the hour.
Is this schedule supported out-of-the-box in AWS EventBridge?
AWS EventBridge uses a different cron syntax (6 fields). To achieve this schedule in AWS, you would use 'cron(0 */4 * * ? *)' or a rate expression like 'rate(4 hours)'.
* Explore
Related expressions you might need
Last verified: