Understanding CRON Expressions: A Complete Guide

2 minute read

What is a CRON Expression?

A CRON expression is a string representing a schedule for executing tasks at specific time intervals. It is commonly used in scheduling jobs in operating systems, cloud services, and automation tools like Azure Functions, Kubernetes, and Unix-based systems.

A CRON expression consists of multiple fields defining the execution time of a scheduled task. The format may vary slightly depending on the system, but the most common format consists of five or six fields:

*  *  *  *  *  *
|  |  |  |  |  |
|  |  |  |  |  +---- Day of the week  (0-6, Sunday = 0 or 7)
|  |  |  |  +------ Month (1-12)
|  |  |  +--------- Day of the month (1-31)
|  |  +------------ Hour (0-23)
|  +--------------- Minute (0-59)
+------------------ Second (0-59) [Only in some systems like Azure Functions]

Why is a CRON Expression Used? CRON expressions are used to schedule tasks automatically without manual intervention. Common use cases include:

  • Automating system tasks – Running backups, log rotation, and system maintenance.
  • Executing scheduled scripts – Running batch jobs or automated reports at specific times.
  • Cloud function scheduling – Triggering AWS Lambda, Azure Functions, or Google Cloud Functions.
  • Database maintenance – Running periodic data cleanups, index rebuilds, or ETL processes.
  • CI/CD pipelines – Scheduling automated deployments or build processes.

How is a CRON Expression Used? CRON expressions are used in various platforms and services. Here are a few common implementations:

  • Unix/Linux CRON Jobs:
    • Add scheduled tasks in the crontab file using crontab -e.
    • Example: 0 2 * * * /path/to/script.sh (Runs a script every day at 2:00 AM)
  • Azure Functions:
    • Uses a six-field CRON format (including seconds).
    • Example: "0 0 * * * *" (Runs every hour on the hour)
  • Kubernetes CronJobs:
    • Defines scheduled jobs in Kubernetes clusters.
    • Example YAML definition:

      apiVersion: batch/v1
      kind: CronJob
      metadata:
        name: example-cronjob
      spec:
        schedule: "0 12 * * *"  # Runs every day at 12:00 PM
      

Examples of CRON Expressions

CRON Expression Meaning
0 0 * * * * Runs every hour on the hour
*/5 * * * * * Runs every 5 seconds (Azure Functions)
0 */15 * * * * Runs every 15 minutes
0 0 12 * * ? Runs every day at 12:00 PM
0 0 1 * * ? Runs on the 1st of every month at midnight
0 0 0 * * 1 Runs every Monday at midnight

Conclusion

CRON expressions are a powerful tool for scheduling tasks in various environments. Whether used for system automation, cloud functions, or database maintenance, understanding CRON syntax helps optimize workflow efficiency. By mastering CRON expressions, you can ensure that tasks run at precise intervals without manual intervention.