Back to Home

Cron Expression: Every 12 Hours (0 */12 * * *)

CronOS Team
cronschedulingevery-12-hoursperiodic-taskstutorial

Need to generate a cron expression?

Use CronOS to generate any cron expression you wish with natural language. Simply describe what you need, and we'll create the perfect cron expression for you. It's completely free!

Generate Cron Expression

Cron Expression: Every 12 Hours (0 */12 * * *)

The cron expression 0 */12 * * * executes a task every 12 hours at the top of the hour (minute 0), making it ideal for periodic backups, data synchronization, and maintenance operations that need to run twice daily.

Expression Breakdown

bash
0 */12 * * *
│  │   │ │ │
│  │   │ │ └─── Day of week: * (every day)
│  │   │ └───── Month: * (every month)
│  │   └─────── Day of month: * (every day)
│  └─────────── Hour: */12 (every 12 hours)
└────────────── Minute: 0 (at minute 0)

Field Values

FieldValueMeaning
Minute0At minute 0 (top of the hour)
Hour*/12Every 12 hours (0, 12)
Day of Month*Every day (1-31)
Month*Every month (1-12)
Day of Week*Every day of week (0-7)

Step Value Syntax

The /12 in the hour field is a step value that means "every 12th hour starting from 0":

  • Runs at: 00:00 (midnight) and 12:00 (noon)

Common Use Cases

1. Periodic Backups

bash
0 */12 * * * /usr/local/bin/backup.sh

Create backups or snapshots of databases and critical files twice daily.

2. Data Synchronization

bash
0 */12 * * * /usr/bin/python3 /scripts/sync-data.py

Sync data between systems, databases, or external services twice daily.

3. Cache Refresh

bash
0 */12 * * * /usr/bin/python3 /scripts/refresh-cache.py

Refresh cached data, computed statistics, or API responses twice daily.

4. Health Monitoring

bash
0 */12 * * * /usr/local/bin/system-health-check.sh

Monitor system health, resource usage, or service availability twice daily.

5. Report Generation

bash
0 */12 * * * /usr/bin/python3 /scripts/generate-report.py

Generate periodic reports or analytics summaries twice daily.

Execution Frequency

This expression runs 2 times per day at:

  • 00:00 (midnight) and 12:00 (noon)

Example Implementations

Backup Script

bash
#!/bin/bash
# /usr/local/bin/backup.sh

BACKUP_DIR="/var/backups/12hourly"
SOURCE_DIR="/var/data"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="/var/log/backups.log"

mkdir -p $BACKUP_DIR

tar -czf "$BACKUP_DIR/backup_$TIMESTAMP.tar.gz" \
    -C $(dirname $SOURCE_DIR) \
    $(basename $SOURCE_DIR) >> $LOG_FILE 2>&1

find $BACKUP_DIR -name "*.tar.gz" -mtime +30 -delete

echo "$(date): 12-hourly backup completed" >> $LOG_FILE

Python Data Sync

python
# sync-data.py
import requests
import json
from datetime import datetime
import sqlite3

def sync_data():
    try:
        response = requests.get(
            'https://api.external.com/data',
            timeout=600,
            headers={'Authorization': 'Bearer YOUR_TOKEN'}
        )
        response.raise_for_status()
        data = response.json()
        
        conn = sqlite3.connect('/var/data/app.db')
        cursor = conn.cursor()
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS synced_data (
                id TEXT PRIMARY KEY,
                data TEXT,
                updated_at TIMESTAMP
            )
        ''')
        
        for item in data:
            cursor.execute('''
                INSERT OR REPLACE INTO synced_data 
                (id, data, updated_at) 
                VALUES (?, ?, ?)
            ''', (item['id'], json.dumps(item), datetime.now()))
        
        conn.commit()
        conn.close()
        
        print(f"{datetime.now()}: Synced {len(data)} records")
    except Exception as e:
        print(f"{datetime.now()}: Sync failed: {e}")

if __name__ == '__main__':
    sync_data()

Best Practices

  1. Execution Time: Tasks should complete within 710-715 minutes
  2. Locking: Use file locks or distributed locks to prevent concurrent execution
  3. Error Handling: Implement comprehensive error handling and logging
  4. Idempotency: Design tasks to be safely re-runnable
  5. Resource Management: Monitor CPU, memory, and I/O usage

When to Use

Good for:

  • Periodic backups (twice daily)
  • Data synchronization
  • Cache refresh operations
  • Health monitoring
  • Report generation
  • Less frequent maintenance tasks

Avoid for:

  • Real-time critical operations
  • Tasks requiring immediate execution
  • Very long-running processes (over 710 minutes)

Comparison with Other Intervals

IntervalExpressionRuns/DayBest For
Every 8 hours0 */8 * * *3More frequent tasks
Every 12 hours0 */12 * * *2Twice daily tasks
Every 24 hours0 0 * * *1Daily tasks
Every 48 hours0 0 */2 * *Every 2 daysLess frequent

Real-World Example

A typical setup for twice-daily operations:

bash
# Periodic backup
0 */12 * * * /usr/local/bin/backup.sh

# Sync external data
0 */12 * * * /usr/bin/python3 /scripts/sync-data.py

# Health check
0 */12 * * * /usr/local/bin/system-health-check.sh

Conclusion

The 0 */12 * * * expression is ideal for tasks that need to run twice daily, typically at midnight and noon. It's perfect for backups, data synchronization, and maintenance operations that don't require more frequent execution, providing a good balance between keeping systems updated and managing resource usage efficiently.

Need to generate a cron expression?

Use CronOS to generate any cron expression you wish with natural language. Simply describe what you need, and we'll create the perfect cron expression for you. It's completely free!

Generate Cron Expression