Back to Home

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

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

The cron expression */10 * * * * executes a task every 10 minutes, providing a practical interval for periodic maintenance, data updates, and regular system checks.

Expression Breakdown

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

Field Values

FieldValueMeaning
Minute*/10Every 10 minutes (0, 10, 20, 30, 40, 50)
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 /10 is a step value that means "every 10th minute starting from 0":

  • Runs at: 00:00, 00:10, 00:20, 00:30, 00:40, 00:50
  • Then repeats every hour: 01:00, 01:10, 01:20, and so on

Common Use Cases

1. Data Synchronization

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

Sync data from external APIs, databases, or third-party services.

2. Log Cleanup

bash
*/10 * * * * /usr/local/bin/cleanup-old-logs.sh

Remove or archive old log files to manage disk space.

3. Cache Warming

bash
*/10 * * * * /usr/local/bin/warm-cache.sh

Pre-load frequently accessed data into cache.

4. Health Checks

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

Monitor application health, database connectivity, or service availability.

5. Metrics Collection

bash
*/10 * * * * /usr/bin/python3 /scripts/collect-metrics.py

Gather and aggregate system or application metrics.

Execution Frequency

This expression runs 6 times per hour (144 times per day) at:

  • :00, :10, :20, :30, :40, :50 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-data.py >> $LOG_FILE 2>&1

# Cleanup
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=30,
            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()
        
        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()

Log Cleanup Script

bash
#!/bin/bash
# /usr/local/bin/cleanup-old-logs.sh

LOG_DIR="/var/log/app"
RETENTION_DAYS=7
ARCHIVE_DIR="/var/log/archive"

# Create archive directory if it doesn't exist
mkdir -p $ARCHIVE_DIR

# Find and archive logs older than retention period
find $LOG_DIR -name "*.log" -type f -mtime +$RETENTION_DAYS | while read logfile; do
    filename=$(basename $logfile)
    archive_path="$ARCHIVE_DIR/${filename}.$(date +%Y%m%d).gz"
    
    # Compress and move
    gzip -c $logfile > $archive_path
    rm $logfile
    
    echo "$(date): Archived $filename to $archive_path"
done

# Clean up archives older than 30 days
find $ARCHIVE_DIR -name "*.gz" -type f -mtime +30 -delete

Node.js Health Check

javascript
// health-check.js
const https = require('https');
const fs = require('fs');

const services = [
  { name: 'API', url: 'https://api.example.com/health' },
  { name: 'Database', url: 'https://db.example.com/health' },
  { name: 'Cache', url: 'https://cache.example.com/health' }
];

async function checkHealth(service) {
  return new Promise((resolve) => {
    https.get(service.url, (res) => {
      const healthy = res.statusCode === 200;
      resolve({ ...service, healthy, status: res.statusCode });
    }).on('error', () => {
      resolve({ ...service, healthy: false, status: 'ERROR' });
    });
  });
}

async function runHealthChecks() {
  const results = await Promise.all(services.map(checkHealth));
  const timestamp = new Date().toISOString();
  
  results.forEach(result => {
    const status = result.healthy ? 'OK' : 'FAIL';
    console.log(`[${timestamp}] ${result.name}: ${status} (${result.status})`);
    
    if (!result.healthy) {
      // Log to file for alerting
      fs.appendFileSync(
        '/var/log/health-checks.log',
        `${timestamp} - ${result.name} is DOWN\n`
      );
    }
  });
}

runHealthChecks().catch(console.error);

Best Practices

  1. Execution Time: Keep tasks under 8-9 minutes to prevent overlap
  2. Locking: Use file locks or distributed locks for critical operations
  3. Error Handling: Implement retry logic and comprehensive logging
  4. Idempotency: Ensure tasks can be safely re-run
  5. Monitoring: Track execution time and success rates

When to Use

Good for:

  • Data synchronization
  • Log cleanup and rotation
  • Cache warming
  • Periodic health checks
  • Metrics collection
  • Background job processing
  • File cleanup operations

Avoid for:

  • Real-time critical operations
  • Tasks requiring immediate execution
  • Very long-running processes
  • Operations needing sub-minute precision

Comparison with Other Intervals

IntervalExpressionRuns/HourUse Case
Every 5 minutes*/5 * * * *12Frequent monitoring
Every 10 minutes*/10 * * * *6Periodic tasks
Every 15 minutes*/15 * * * *4Standard intervals
Every 30 minutes*/30 * * * *2Less frequent tasks

Real-World Example

A typical setup for a web application:

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

# Clean up old logs
*/10 * * * * /usr/local/bin/cleanup-old-logs.sh

# Health check
*/10 * * * * /usr/bin/node /app/health-check.js

Conclusion

The */10 * * * * expression is well-suited for periodic maintenance tasks and data synchronization. It provides a good balance between keeping data fresh and minimizing system resource usage, making it ideal for many production workloads.

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