Twice-Daily 8 AM and 8 PM Cron Schedule | CronBase
0 8,20 * * * Twice daily, once in the morning and once in the evening.
The `0 8,20 * * *` cron expression schedules a task to run twice every day, specifically at 8:00 AM and 8:00 PM. This twelve-hour interval is highly effective for synchronizing databases, generating morning and evening reports, or performing routine system maintenance during shift transitions without disrupting standard business operations.
- Minute
- 0
- Hour
- 8,20
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 11h 19m
- in 23h 19m
- in 1d 11h
- in 1d 23h
- in 2d 11h
* Tools
Code & Implementations
#!/usr/bin/env bash
# System crontab installation instructions:
# 1. Run 'crontab -e' to edit the user's crontab file
# 2. Add the following line to execute twice daily at 8 AM and 8 PM
# 0 8,20 * * * /usr/local/bin/run-sync-job.sh >> /var/log/sync-job.log 2>&1
set -euo pipefail
LOCKFILE="/var/tmp/sync-job.lock"
# Prevent overlapping executions using a file lock
exec 9>>"$LOCKFILE"
if ! flock -n 9; then
echo "[$(date)] Job is already running. Exiting to prevent overlap." >&2
exit 1
fi
echo "[$(date)] Starting twice-daily synchronization task..."
# Place your production logic here (e.g., database synchronization, API polling)
/usr/bin/curl -f -s https://api.example.com/sync || {
echo "[$(date)] Error: Sync API call failed" >&2
exit 1
}
echo "[$(date)] Task completed successfully." › Setup notes
Place the script in /usr/local/bin/run-sync-job.sh, make it executable with chmod +x, and add the cron definition line to your system crontab using crontab -e.
const cron = require('node-cron');
const { exec } = require('child_process');
// Schedule task to run twice daily at 8:00 AM and 8:00 PM
const task = cron.schedule('0 8,20 * * *', () => {
console.log(`[${new Date().toISOString()}] Initiating twice-daily reporting pipeline...`);
try {
// Execute your business logic or external shell scripts here
exec('/usr/local/bin/generate-report.sh', (error, stdout, stderr) => {
if (error) {
console.error(`Execution error: ${error.message}`);
return;
}
if (stderr) {
console.warn(`Warnings: ${stderr}`);
}
console.log(`Pipeline output: ${stdout.trim()}`);
});
} catch (err) {
console.error('Unexpected scheduler execution error:', err);
}
}, {
scheduled: true,
timezone: "UTC"
});
console.log('Twice-daily scheduler initialized for 08:00 and 20:00 UTC.'); › Setup notes
Install the standard dependency using npm install node-cron and run this daemon process using a process manager like PM2 to guarantee uptime.
import logging
import sys
from apscheduler.schedulers.blocking import BlockingScheduler
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
def twice_daily_maintenance():
logging.info("Starting twice-daily database cleanup and indexing...")
try:
# Perform database vacuuming, log rotation, or queue processing
# Example: db.execute("VACUUM ANALYZE;")
logging.info("Maintenance task completed successfully.")
except Exception as e:
logging.error(f"Maintenance task failed: {str(e)}", exc_info=True)
if __name__ == '__main__':
scheduler = BlockingScheduler(timezone="UTC")
# Registering the job to run twice daily at 8 AM and 8 PM
scheduler.add_job(twice_daily_maintenance, 'cron', hour='8,20', minute=0)
logging.info("Scheduler started. Running twice daily at 08:00 and 20:00 UTC.")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logging.info("Scheduler stopped.") › Setup notes
Install APScheduler using pip install apscheduler and execute the script. It will run in the foreground, triggering the job exactly at 08:00 and 20:00 UTC.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
// Use UTC to prevent DST issues
loc, err := time.LoadLocation("UTC")
if err != nil {
log.Fatalf("Failed to load UTC location: %v", err)
}
c := cron.New(cron.WithLocation(loc))
_, err = c.AddFunc("0 8,20 * * *", func() {
log.Println("Starting twice-daily API cache warm-up...")
performWarmup()
})
if err != nil {
log.Fatalf("Failed to register cron job: %v", err)
}
c.Start()
log.Println("Cron engine running. Scheduled twice daily at 08:00 and 20:00 UTC.")
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Shutting down cron engine...")
ctx := c.Stop()
<-ctx.Done()
log.Println("Scheduler stopped.")
}
func performWarmup() {
// Application logic goes here
log.Println("Cache warm-up completed.")
} › Setup notes
Initialize a Go module, run go get github.com/robfig/cron/v3, and build the binary to run as a background system service.
package com.example.scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TwiceDailyTaskExecutor {
private static final Logger logger = LoggerFactory.getLogger(TwiceDailyTaskExecutor.class);
// Spring Cron format includes seconds: "sec min hour day month day-of-week"
// Runs daily at 08:00:00 and 20:00:00 UTC
@Scheduled(cron = "0 0 8,20 * * *", zone = "UTC")
public void executeDailyTasks() {
logger.info("Initiating twice-daily batch pipeline execution...");
try {
// Add business logic execution here
runBatchPipeline();
logger.info("Batch pipeline completed successfully.");
} catch (Exception e) {
logger.error("Critical failure in twice-daily pipeline execution", e);
}
}
private void runBatchPipeline() {
// Actual processing logic
}
} › Setup notes
Ensure @EnableScheduling is added to your main Spring Boot Application class. The class must be a Spring-managed component (e.g., @Component).
apiVersion: batch/v1
kind: CronJob
metadata:
name: twice-daily-sync
namespace: production
spec:
schedule: "0 8,20 * * *"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 600
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: sync-worker
image: registry.example.com/data-sync:v2.4.1
command:
- /app/run-sync.sh
resources:
limits:
cpu: "1"
memory: 1Gi
requests:
cpu: "500m"
memory: 512Mi
restartPolicy: OnFailure › Setup notes
Apply this manifest using kubectl apply -f cronjob.yaml. The concurrencyPolicy: Forbid ensures that if a run takes longer than 12 hours, the next run is skipped.
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,20 * * ? *) Systemd Timer
OnCalendar*-*-* 08,20:00:00
[Unit]
Description=Timer for cron expression: 0 8,20 * * *
[Timer]
OnCalendar=*-*-* 08,20:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
How do I handle daylight saving time shifts for this twice-daily schedule?
If your server runs on local time, DST transitions in spring and autumn might cause the 8 AM or 8 PM runs to execute twice or be skipped entirely. To prevent this, standardise your system clock to UTC, which does not observe DST, and adjust your cron schedule offset manually if business requirements dictate local time alignment.
What happens if the 8 AM execution is still running when the 8 PM execution starts?
If a run exceeds 12 hours, standard cron will spawn a concurrent process, potentially causing database lock contention or race conditions. Implement a locking mechanism such as `flock` in Bash, a distributed lock manager like Redis (Redlock) in your application code, or set `concurrencyPolicy: Forbid` in Kubernetes.
How can I add a randomized delay to prevent simultaneous resource spikes?
To avoid overloading downstream APIs or databases at exactly 8:00, introduce a random sleep or jitter. In Bash, you can prepend `sleep $((RANDOM % 300))` to delay execution by up to 5 minutes, or handle this programmatically within your application code before executing the main business logic.
Can I run this schedule only on weekdays instead of every day?
Yes, you can modify the fifth field of the cron expression. Changing the expression to `0 8,20 * * 1-5` will restrict the twice-daily execution to Monday through Friday, skipping weekends entirely.
How should I monitor and alert on failures for this specific twice-daily cadence?
Configure dead man's snitches or heartbeat monitoring (like Healthchecks.io or Prometheus alertmanager) with an expected check-in interval of 12 hours. If the system fails to check in within a defined grace period (e.g., 13 hours), trigger high-priority paging alerts to your on-call engineering team.
* Explore
Related expressions you might need
Last verified: