Run Every 8 Hours Cron Schedule | CronBase
0 */8 * * * Every eight hours at the very beginning of the hour.
The `0 */8 * * *` cron expression schedules a task to run exactly every eight hours, specifically at midnight, eight in the morning, and four in the afternoon. This three-times-daily interval is commonly used for intermediate database backups, log rotation, system health checks, and periodic API data synchronization.
- Minute
- 0
- Hour
- */8
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 3h 22m
- in 11h 22m
- in 19h 22m
- in 1d 3h
- in 1d 11h
* Tools
Code & Implementations
#!/usr/bin/env bash
# Production-ready Bash wrapper for 8-hour cron job
set -euo pipefail
LOCKFILE="/var/lock/eight_hour_backup.lock"
exec 9>"$LOCKFILE"
# Acquire exclusive non-blocking lock to prevent overlapping runs
if ! flock -n 9; then
echo "Error: Another instance of this job is already running." >&2
exit 1
fi
echo "[$(date -u)] Starting 8-hour system maintenance task..."
# Real task execution
/usr/local/bin/backup-db.sh --target s3://my-bucket/backups
echo "[$(date -u)] Task completed successfully." › Setup notes
Save this script to /usr/local/bin/run-backup.sh, make it executable with chmod +x, and add '0 */8 * * * /usr/local/bin/run-backup.sh' to your crontab.
// Node.js 8-hour cron scheduler using 'node-cron'
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule: 0 */8 * * * (Every 8 hours at minute 0)
cron.schedule('0 */8 * * *', () => {
console.log(`[${new Date().toISOString()}] Initiating scheduled data sync...`);
exec('/usr/bin/node /app/sync.js', (error, stdout, stderr) => {
if (error) {
console.error(`[Error] Execution failed: ${error.message}`);
return;
}
if (stderr) {
console.warn(`[Warning] Stderr output: ${stderr}`);
}
console.log(`[Success] Sync output: ${stdout}`);
});
}, {
scheduled: true,
timezone: "UTC"
}); › Setup notes
Install node-cron using 'npm install node-cron' and run this script as a daemon process using PM2 or systemd.
# Python 8-hour scheduler using APScheduler
import logging
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def execute_eight_hour_task():
logger.info("Starting the 8-hour database optimization routine.")
try:
# Place actual production logic here
pass
logger.info("Database optimization completed successfully.")
except Exception as e:
logger.error(f"Task failed with exception: {str(e)}", exc_info=True)
if __name__ == "__main__":
scheduler = BlockingScheduler()
# 0 */8 * * * equivalent trigger
trigger = CronTrigger(minute=0, hour='*/8', timezone='UTC')
scheduler.add_job(execute_eight_hour_task, trigger=trigger, id='eight_hour_job')
logger.info("Scheduler initialized. Running job every 8 hours on UTC.")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logger.info("Scheduler stopped cleanly.") › Setup notes
Install APScheduler via 'pip install apscheduler' and run this script as a persistent background service.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "[CRON] ", log.LstdFlags|log.Lshortfile)
// Configure cron with UTC location
c := cron.New(cron.WithLocation(time.UTC))
_, err := c.AddFunc("0 */8 * * *", func() {
logger.Println("Executing 8-hour background task...")
if err := performTask(); err != nil {
logger.Printf("ERROR: Task execution failed: %v\n", err)
} else {
logger.Println("SUCCESS: Task completed.")
}
})
if err != nil {
logger.Fatalf("Failed to schedule cron job: %v", err)
}
c.Start()
logger.Println("Cron scheduler started running every 8 hours (UTC)")
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down scheduler...")
c.Stop()
}
func performTask() error {
// Production logic goes here
return nil
} › Setup notes
Import 'github.com/robfig/cron/v3', compile the binary using 'go build', and execute it inside your production environment.
package com.cronbase.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class EightHourScheduler {
private static final Logger logger = LoggerFactory.getLogger(EightHourScheduler.class);
// Spring's @Scheduled annotation supports standard 6-field cron (adding seconds)
// Here we use standard Spring cron format: "0 0 */8 * * *" (sec min hour day month day-of-week)
@Scheduled(cron = "0 0 */8 * * *", zone = "UTC")
public void executeEightHourJob() {
logger.info("Starting scheduled 8-hour batch processing job...");
try {
runBatchProcess();
logger.info("Batch processing completed successfully.");
} catch (Exception e) {
logger.error("Critical error during 8-hour batch execution", e);
// Implement alert dispatching/monitoring notification here
}
}
private void runBatchProcess() throws Exception {
// Actual business logic execution
}
} › Setup notes
Ensure @EnableScheduling is added to your main Spring Boot Application class and place this component in your scanned package paths.
apiVersion: batch/v1
kind: CronJob
metadata:
name: eight-hour-cleanup
namespace: production
spec:
schedule: "0 */8 * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: cleanup-worker
image: redis:7.0-alpine
command: ["redis-cli", "-h", "redis-master", "FLUSHDB"]
resources:
limits:
cpu: "100m"
memory: "128Mi"
requests:
cpu: "50m"
memory: "64Mi"
restartPolicy: OnFailure › Setup notes
Apply this configuration to your Kubernetes cluster using 'kubectl apply -f cronjob.yaml' in your specified namespace.
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 */8 * * ? *) Systemd Timer
OnCalendar*-*-* 00/8:00:00
[Unit]
Description=Timer for cron expression: 0 */8 * * *
[Timer]
OnCalendar=*-*-* 00/8:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I offset this job to avoid top-of-the-hour traffic spikes?
You can change the first field (minutes) to a specific offset, such as `15 */8 * * *` to run at 15 minutes past the hour, or `42 */8 * * *` to run at 42 minutes past. This distributes load and prevents resource contention.
Will this job run exactly three times a day during DST transitions?
If your cron daemon runs on local server time in a region with DST, the job may run twice or four times on transition days, with intervals of 7 or 9 hours. To prevent this, always configure your cron daemon or scheduler to evaluate in UTC.
What happens if a run takes longer than 8 hours to complete?
Standard cron will launch a new process even if the previous one is still running. This can lead to race conditions and memory exhaustion. Use locking mechanisms like `flock` in Bash, Redis locks, or Kubernetes' `concurrencyPolicy: Forbid` to prevent overlaps.
How can I test this schedule locally without waiting 8 hours?
For testing purposes, temporarily modify the expression to `*/5 * * * *` (every 5 minutes) or run the target script/command directly outside of the cron daemon to verify its functionality and output handling.
Is there a difference between `0 */8 * * *` and `0 0,8,16 * * *`?
No, they are functionally identical in standard cron. Both schedule executions at 00:00, 08:00, and 16:00. The list syntax `0,8,16` is sometimes preferred for explicit clarity, while the step syntax `*/8` is more concise.
* Explore
Related expressions you might need
Last verified: