Run Daily 6 PM Tasks Efficiently | CronBase
0 18 * * * Every day in the evening at six PM.
The `0 18 * * *` cron expression schedules a task to execute every day precisely at 18:00 (6:00 PM) in the system's local timezone. It is widely used for executing end-of-day business processes, daily database backups, generating financial reports, and initiating routine maintenance tasks after standard working hours.
- Minute
- 0
- Hour
- 18
- Day of Month
- *
- Month
- *
- Day of Week
- *
Next 5 Runs
- in 21h 19m
- in 1d 21h
- in 2d 21h
- in 3d 21h
- in 4d 21h
* Tools
Code & Implementations
#!/usr/bin/env bash
set -euo pipefail
# Lock file to prevent concurrent execution if a previous job is still running
LOCKFILE="/var/tmp/daily_backup_1800.lock"
exec 9>>"$LOCKFILE"
if ! flock -n 9; then
echo "[$(date)] Error: Another instance of the daily 6 PM backup job is already running." >&2
exit 1
fi
echo "[$(date)] Starting daily end-of-day synchronization task..."
# Place your actual production task execution here
# Example: pg_dump -U db_user -h db_host production_db > /backups/daily_$(date +%F).sql
echo "[$(date)] End-of-day synchronization completed successfully." › Setup notes
Save this script as /usr/local/bin/daily_backup.sh, make it executable with chmod +x, and add the following entry to your system crontab using crontab -e:
0 18 * * * /usr/local/bin/daily_backup.sh >> /var/log/daily_backup.log 2>&1
const cron = require('node-cron');
const { exec } = require('child_process');
console.log('Registering daily 6 PM worker schedule...');
// Schedule task to run daily at 18:00 (6:00 PM)
cron.schedule('0 18 * * *', () => {
console.log(`[${new Date().toISOString()}] Initiating daily batch processing...`);
exec('/usr/local/bin/run-batch-processing.sh', (error, stdout, stderr) => {
if (error) {
console.error(`[${new Date().toISOString()}] Execution Error: ${error.message}`);
return;
}
if (stderr) {
console.warn(`[${new Date().toISOString()}] Warning output: ${stderr}`);
}
console.log(`[${new Date().toISOString()}] Batch processing completed: ${stdout}`);
});
}, {
scheduled: true,
timezone: "America/New_York"
}); › Setup notes
Install the required dependency using npm install node-cron. Run the script in a persistent process manager such as PM2 to guarantee continuous uptime.
import logging
import sys
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')
def execute_daily_sync():
logging.info("Starting daily 6 PM database synchronization task...")
try:
# Simulate production integration task
# response = requests.post('https://api.internal/v1/sync', timeout=120)
# response.raise_for_status()
logging.info("Daily database synchronization completed successfully.")
except Exception as e:
logging.error(f"Critical failure during daily synchronization: {str(e)}")
# Implement your alerting system here (e.g., PagerDuty, Slack webhook)
if __name__ == '__main__':
scheduler = BlockingScheduler()
trigger = CronTrigger(hour=18, minute=0, timezone='UTC')
scheduler.add_job(execute_daily_sync, trigger=trigger, id='daily_sync_job')
logging.info("Scheduler started. Daily sync job queued for 18:00 UTC.")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
logging.info("Scheduler stopped gracefully.")
sys.exit(0) › Setup notes
Install APScheduler via pip: pip install apscheduler. Run this script as a systemd service or inside a Docker container for production environments.
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/robfig/cron/v3"
)
func main() {
logger := log.New(os.Stdout, "[DailyCron] ", log.LstdFlags|log.Lshortfile)
// Initialize cron with explicit timezone support
nyc, err := time.LoadLocation("America/New_York")
if err != nil {
logger.Fatalf("Failed to load timezone: %v", err)
}
c := cron.New(cron.WithLocation(nyc))
_, err = c.AddFunc("0 18 * * *", func() {
logger.Println("Executing daily scheduled task...")
// Perform production task (e.g., clearing stale cache, rotating logs)
performMaintenance(logger)
})
if err != nil {
logger.Fatalf("Error scheduling job: %v", err)
}
c.Start()
logger.Println("Cron engine initialized. Job scheduled daily at 18:00 EST/EDT.")
// Keep application running until interrupted
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
logger.Println("Shutting down cron engine...")
c.Stop()
}
func performMaintenance(logger *log.Logger) {
// Realistic task simulation
time.Sleep(5 * time.Second)
logger.Println("Scheduled maintenance completed successfully.")
} › Setup notes
Initialize your Go module, fetch the robfig/cron package with go get github.com/robfig/cron/v3, and run using go run main.go.
package com.cronbase.scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Instant;
@Component
public class DailyTaskScheduler {
private static final Logger logger = LoggerFactory.getLogger(DailyTaskScheduler.class);
// Runs daily at 18:00 (6:00 PM) in the configured application timezone
@Scheduled(cron = "0 0 18 * * *", zone = "UTC")
public void runDailyReportGeneration() {
logger.info("Starting end-of-day financial report generation at {}", Instant.now());
try {
// Business logic implementation
generateReports();
logger.info("End-of-day financial reports successfully generated.");
} catch (Exception ex) {
logger.error("Critical failure executing daily report generation: ", ex);
// Trigger emergency monitoring notification
}
}
private void generateReports() throws InterruptedException {
// Simulate database query and processing time
Thread.sleep(10000);
}
} › Setup notes
Ensure @EnableScheduling is added to your main Spring Boot configuration class. Note that Spring's CronTrigger expects 6 fields (adding seconds as the first parameter).
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-reconciliation-job
namespace: production
spec:
schedule: "0 18 * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: reconciliation-worker
image: registry.internal/reconciliation-service:v2.1.0
imagePullPolicy: IfNotPresent
env:
- name: NODE_ENV
value: "production"
resources:
limits:
cpu: "1000m"
memory: "1Gi"
requests:
cpu: "500m"
memory: "512Mi"
restartPolicy: OnFailure › Setup notes
Apply this configuration to your cluster using kubectl apply -f cronjob.yaml. Check execution history using kubectl get cronjob daily-reconciliation-job -n production.
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 18 * * ? *) Systemd Timer
OnCalendar*-*-* 18:00:00
[Unit]
Description=Timer for cron expression: 0 18 * * *
[Timer]
OnCalendar=*-*-* 18:00:00
Persistent=true
[Install]
WantedBy=timers.target
Last verified:
Frequently Asked Questions
What happens to a 6 PM cron job during Daylight Saving Time (DST) changes?
If your system timezone is set to a region observing DST (like America/New_York), the job will execute at 18:00 local time year-round. However, this means the interval between runs will be 23 hours in the spring and 25 hours in the autumn. To maintain strict 24-hour intervals, run your servers and cron engines in UTC.
How can I prevent a long-running 18:00 job from overlapping with the next day's run?
For standard cron, wrap your script with the `flock` utility to enforce a file lock. In Kubernetes, configure `concurrencyPolicy: Forbid` in your CronJob spec. For application-level tasks, implement distributed locking with Redis (Redlock) or database-backed locks.
Is 18:00 (6:00 PM) a good time to schedule intensive database backups?
Only if your user base is inactive at that time. For many business-to-business (B2B) applications, 18:00 local time is when users log off, making it ideal. However, for global or consumer-facing services, 18:00 represents peak evening traffic. Analyze your traffic patterns and schedule heavy IO tasks during off-peak windows.
How do I test my daily 18:00 job without waiting until 6 PM?
You can trigger the job manually. In Kubernetes, use `kubectl create job --from=cronjob/daily-reconciliation-job test-job`. In Linux systems, run the target script directly with the same environment variables as the cron daemon, or temporarily modify the schedule to run a few minutes from the current time.
Why did my daily 18:00 cron job fail to execute silently?
Silent failures are usually caused by the cron daemon dying, the target script lacking execution permissions, or missing environment variables. Cron runs with a highly restricted path environment. Always use absolute paths for executables and redirect both stdout and stderr to a log file or an external monitoring platform.
* Explore
Related expressions you might need
Last verified: