Back to Home

Cron Expression: Every 45 Minutes (*/45 * * * *)

CronOS Team
cronschedulingevery-45-minutesperiodic-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 45 Minutes (*/45 * * * *)

The cron expression */45 * * * * executes a task every 45 minutes, providing an uncommon but useful interval for periodic maintenance and data synchronization tasks.

Expression Breakdown

bash
*/45 * * * *
│    │ │ │ │
│    │ │ │ └─── Day of week: * (every day)
│    │ │ └───── Month: * (every month)
│    │ └─────── Day of month: * (every day)
│    └───────── Hour: * (every hour)
└────────────── Minute: */45 (every 45 minutes)

Field Values

FieldValueMeaning
Minute*/45Every 45 minutes (0, 45)
Hour*Every hour (0-23)
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 /45 is a step value that means "every 45th minute starting from 0":

  • Runs at: 00:00, 00:45
  • Then repeats every hour: 01:00, 01:45, 02:00, 02:45, and so on

Common Use Cases

1. Data Synchronization

bash
*/45 * * * * /usr/bin/python3 /scripts/sync-external-data.py

Sync data from external APIs or services at regular intervals.

2. Cache Refresh

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

Refresh cached data, computed statistics, or API responses.

3. Periodic Maintenance

bash
*/45 * * * * /usr/local/bin/maintenance.sh

Run periodic maintenance tasks, cleanup operations, or optimizations.

4. Health Checks

bash
*/45 * * * * /usr/local/bin/health-check.sh

Monitor application health, service availability, or system resources.

5. Backup Operations

bash
*/45 * * * * /usr/local/bin/incremental-backup.sh

Create incremental backups or snapshots of critical data.

Execution Frequency

This expression runs approximately 1.33 times per hour (32 times per day) at:

  • :00 and :45 of every hour

Example Implementations

Data Synchronization Script

bash
#!/bin/bash
# /usr/local/bin/sync-external-data.sh

LOCK_FILE="/tmp/sync-data.lock"
LOG_FILE="/var/log/sync-data.log"

# Prevent concurrent execution
if [ -f "$LOCK_FILE" ]; then
    echo "$(date): Sync already running, skipping" >> $LOG_FILE
    exit 0
fi

touch $LOCK_FILE

# Sync data
/usr/bin/python3 /scripts/sync-external-data.py >> $LOG_FILE 2>&1

rm -f $LOCK_FILE

Python Data Sync

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

def sync_data():
    try:
        # Fetch from external API
        response = requests.get(
            'https://api.external.com/data',
            timeout=60,
            headers={'Authorization': 'Bearer YOUR_TOKEN'}
        )
        response.raise_for_status()
        data = response.json()
        
        # Store in local database
        conn = sqlite3.connect('/var/data/app.db')
        cursor = conn.cursor()
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS external_data (
                id TEXT PRIMARY KEY,
                data TEXT,
                updated_at TIMESTAMP
            )
        ''')
        
        for item in data:
            cursor.execute('''
                INSERT OR REPLACE INTO external_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()

Cache Refresh Script

python
# refresh-cache.py
import redis
import requests
from datetime import datetime

def refresh_cache():
    r = redis.Redis(host='localhost', port=6379, db=0)
    
    try:
        # Fetch fresh data
        response = requests.get('https://api.example.com/data', timeout=30)
        response.raise_for_status()
        data = response.json()
        
        # Update cache with 1 hour TTL
        r.setex('cached_data', 3600, json.dumps(data))
        
        # Cache individual items
        for item in data:
            r.setex(f"item:{item['id']}", 3600, json.dumps(item))
        
        print(f"{datetime.now()}: Cache refreshed with {len(data)} items")
    except Exception as e:
        print(f"{datetime.now()}: Cache refresh failed: {e}")

if __name__ == '__main__':
    refresh_cache()

Health Check Script

bash
#!/bin/bash
# /usr/local/bin/health-check.sh

LOG_FILE="/var/log/health-checks.log"
ALERT_THRESHOLD=3

check_service() {
    local service_name=$1
    local service_url=$2
    
    if curl -sf "$service_url" > /dev/null 2>&1; then
        echo "$(date): $service_name - OK" >> $LOG_FILE
        return 0
    else
        echo "$(date): $service_name - FAILED" >> $LOG_FILE
        return 1
    fi
}

# Check multiple services
check_service "API" "https://api.example.com/health"
check_service "Database" "https://db.example.com/health"
check_service "Cache" "https://cache.example.com/health"

# Count failures in last hour
FAILURES=$(grep "$(date +%Y-%m-%d)" $LOG_FILE | grep -c "FAILED" | tail -20)

if [ $FAILURES -ge $ALERT_THRESHOLD ]; then
    echo "$(date): ALERT - Multiple service failures detected" >> $LOG_FILE
    # Send alert notification
    /usr/local/bin/send-alert.sh "Multiple service failures"
fi

Best Practices

  1. Execution Time: Tasks should complete within 40-42 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:

  • Data synchronization
  • Cache refresh operations
  • Periodic maintenance
  • Health monitoring
  • Incremental backups
  • Less frequent but regular tasks

Avoid for:

  • Real-time critical operations
  • Tasks requiring immediate execution
  • Very long-running processes (over 40 minutes)
  • Operations needing precise timing

Comparison with Other Intervals

IntervalExpressionRuns/HourBest For
Every 30 minutes*/30 * * * *2More frequent tasks
Every 45 minutes*/45 * * * *~1.33Less frequent tasks
Every hour0 * * * *1Hourly tasks
Every 2 hours0 */2 * * *12/dayEven less frequent

Real-World Example

A typical setup for periodic data synchronization:

bash
# Sync external data
*/45 * * * * /usr/bin/python3 /scripts/sync-external-data.py

# Refresh cache
*/45 * * * * /usr/bin/python3 /scripts/refresh-cache.py

# Health check
*/45 * * * * /usr/local/bin/health-check.sh

Conclusion

The */45 * * * * expression is useful for tasks that need regular execution but can tolerate a 45-minute interval. While less common than 15, 30, or 60-minute intervals, it can be ideal for specific use cases where this timing fits your operational requirements.

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