Parser de Cron

Analise e explique expressões cron em linguagem natural com contexto de agendamento

What is a Cron Expression?

A cron expression is a compact string that defines a recurring schedule using a series of time-and-date fields. Originally introduced in Unix System V (circa 1975) and later standardized in the POSIX specification (IEEE Std 1003.1), cron expressions remain the universal language for scheduling automated tasks across operating systems, cloud platforms, CI/CD pipelines, and container orchestrators. A standard POSIX cron expression uses five fields — minute, hour, day of month, month, and day of week — separated by whitespace, where each field can contain specific values, ranges, step intervals, or wildcards. Modern implementations extend this to six fields by prepending a seconds field, enabling sub-minute scheduling for applications that require higher precision.

Cron Expression Syntax: The Five-Field Format

The standard POSIX cron format consists of five fields, each representing a unit of time. From left to right the fields are:

  • Minute (0–59): The minute within the hour when the job fires.
  • Hour (0–23): The hour of the day in 24-hour format.
  • Day of Month (1–31): The calendar day. Not all months have 31 days, so values above 28 may be skipped in shorter months.
  • Month (1–12 or JAN–DEC): The month of the year. Numeric and abbreviated name forms are both accepted in most implementations.
  • Day of Week (0–7 or SUN–SAT): The weekday, where both 0 and 7 represent Sunday in POSIX cron. Some implementations accept 1–7 with Monday as 1.

Extended six-field cron expressions prepend a Seconds field (0–59) before the minute field. This format is common in Spring Framework (@Scheduled), Quartz Scheduler, and AWS EventBridge rate/cron rules. When reading a cron expression, always verify whether the system uses 5-field (POSIX) or 6-field (extended) format, as misinterpreting the field positions is the most common source of scheduling bugs.

Special Characters and Operators

Cron expressions support several special characters that provide flexibility beyond fixed values:

  • Asterisk (*): Matches every possible value in the field. * * * * * means every minute of every hour of every day.
  • Comma (,): Specifies a list of discrete values. 1,15,30 in the minute field fires at minutes 1, 15, and 30.
  • Hyphen (-): Defines an inclusive range. 9-17 in the hour field matches every hour from 9 AM to 5 PM.
  • Slash (/): Defines a step interval. */5 in the minute field means every 5 minutes (0, 5, 10, 15…). 10-30/5 means every 5 minutes between minute 10 and 30.

Some implementations add further operators: L (last day of month/week), W (nearest weekday), # (nth weekday of month), and ? (no specific value, used when day-of-month and day-of-week conflict). These are non-standard extensions found in Quartz and Spring but not in POSIX cron.

Common Schedule Patterns and Shorthand Aliases

Many cron implementations support predefined shorthand aliases as a convenience for frequently used schedules:

  • @yearly (or @annually): Equivalent to 0 0 1 1 * — runs at midnight on January 1st.
  • @monthly: Equivalent to 0 0 1 * * — runs at midnight on the 1st of each month.
  • @weekly: Equivalent to 0 0 * * 0 — runs at midnight every Sunday.
  • @daily (or @midnight): Equivalent to 0 0 * * * — runs once daily at midnight.
  • @hourly: Equivalent to 0 * * * * — runs at minute 0 of every hour.
  • @reboot: Runs once at system startup (not time-based, non-standard in pure POSIX).

Common manual patterns include: 0 9 * * 1-5 (weekdays at 9 AM), */10 * * * * (every 10 minutes), 0 0 * * 0 (weekly Sunday at midnight), 30 2 1,15 * * (2:30 AM on the 1st and 15th of each month), and 0 */6 * * * (every 6 hours). When writing schedules, always consider the timezone context — a job scheduled at 0 3 * * * runs at 3 AM in the system's configured timezone, which may shift during daylight saving transitions.

Timezone Considerations and Daylight Saving

POSIX cron evaluates expressions against the system's local timezone. This creates subtle issues during daylight saving time (DST) transitions. When clocks spring forward (e.g., 2:00 AM → 3:00 AM), jobs scheduled between 2:00 and 2:59 AM may be skipped entirely. When clocks fall back, jobs in the repeated hour may execute twice.

Modern schedulers address this differently: Kubernetes CronJobs use the timeZone field (stable since v1.27) to pin schedules to a specific IANA timezone. AWS EventBridge evaluates cron in UTC by default. systemd timers support OnCalendar= with explicit timezone specifiers. GitHub Actions cron triggers always evaluate in UTC. When scheduling critical jobs, prefer UTC-based scheduling or explicitly document the timezone assumption to avoid DST-related missed or double executions.

Cron in Modern Systems

While the cron daemon (crond) remains the default scheduler on Linux and macOS, cron expressions have been adopted far beyond traditional Unix systems:

  • Kubernetes CronJobs: Schedule containerized workloads using standard 5-field cron expressions with optional timezone.
  • GitHub Actions: The schedule trigger accepts cron expressions (UTC only, minimum interval 5 minutes).
  • AWS CloudWatch / EventBridge: Uses 6-field cron (includes year) or rate expressions for Lambda triggers and Step Functions.
  • CI/CD pipelines: GitLab CI, CircleCI, and Jenkins all support cron-based pipeline scheduling for nightly builds and periodic tests.
  • Database maintenance: PostgreSQL pg_cron extension and MySQL Event Scheduler use cron-like syntax for vacuum, backup, and partition management.

Understanding cron syntax is a foundational skill for DevOps, SRE, and backend engineering roles. Whether you are configuring log rotation, scheduling database backups, triggering deployment pipelines, or running periodic health checks, cron expressions provide a concise and universal way to express recurring schedules across virtually every platform in the modern infrastructure stack.

Code Examples

Parsing and validating cron expressions in Node.js

// Using cron-parser library (npm install cron-parser)
import { parseExpression } from 'cron-parser';

// Parse a cron expression and get next execution times
const expression = parseExpression('*/15 9-17 * * 1-5', {
  tz: 'America/New_York'
});

// Get the next 5 scheduled times
for (let i = 0; i < 5; i++) {
  const next = expression.next();
  console.log(next.toString());
}
// → Mon Jul 14 2025 09:00:00 GMT-0400
// → Mon Jul 14 2025 09:15:00 GMT-0400
// → Mon Jul 14 2025 09:30:00 GMT-0400
// → Mon Jul 14 2025 09:45:00 GMT-0400
// → Mon Jul 14 2025 10:00:00 GMT-0400

// Validate a cron expression
function isValidCron(expr) {
  try {
    parseExpression(expr);
    return true;
  } catch (e) {
    return false;
  }
}

console.log(isValidCron('0 3 * * *'));    // true
console.log(isValidCron('60 * * * *'));   // false (minute > 59)

Cron expressions in Kubernetes CronJob manifest

# Kubernetes CronJob — runs database backup every day at 2:30 AM UTC
apiVersion: batch/v1
kind: CronJob
metadata:
  name: db-backup
spec:
  schedule: "30 2 * * *"
  timeZone: "UTC"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: postgres:16
            command: ["pg_dump", "-h", "db-host", "-U", "admin", "mydb"]
          restartPolicy: OnFailure

Standards & Specifications

Perguntas Frequentes

What is a cron expression?

A cron expression is a string that defines a schedule for recurring tasks. It consists of 5 or 6 fields representing minute, hour, day of month, month, day of week, and optionally year. For example, '0 9 * * 1' means 'every Monday at 9:00 AM'.

What do the asterisks mean?

An asterisk (*) means 'every' or 'any'. For example, * in the hour field means every hour, and * in the day field means every day. It's a wildcard that matches all possible values for that field.

Can I use special characters like L or #?

Support for special characters depends on the cron implementation. Standard cron uses *, -, ,, and /. Extended versions (like Quartz) support L (last), W (weekday), # (nth occurrence), and ?. The tool will indicate which syntax is supported.

Is my data sent to a server?

No, all cron parsing happens in your browser. Your expressions never leave your device. This ensures complete privacy and security.