Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cron Expression Laravel Package

mtdowling/cron-expression

A PHP library for parsing and evaluating cron expressions. Check whether a schedule is due, get next/previous run dates, and iterate occurrences. Supports standard cron fields plus common extensions, useful for job schedulers and task runners.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require mtdowling/cron-expression
    
    • No additional configuration is needed; the package is autoloaded via Composer.
  2. Basic Usage

    use Cron\CronExpression;
    
    $expression = CronExpression::factory('* * * * *'); // Every minute
    $nextRun = $expression->getNextRunDate();
    $isDue = $expression->isDue();
    
  3. First Use Case: Scheduling a Command

    $cron = CronExpression::factory('0 12 * * 1'); // Every Monday at noon
    if ($cron->isDue()) {
        Artisan::call('backup:run');
    }
    

Implementation Patterns

Common Workflows

  1. Parsing and Validation

    $expression = CronExpression::factory('*/15 * * * *'); // Every 15 minutes
    $isValid = $expression->isValid(); // true/false
    
    • Useful for validating user-input cron strings (e.g., in admin panels).
  2. Time Zone Awareness

    $expression = CronExpression::factory('0 0 * * *', new \DateTimeZone('America/New_York'));
    $nextRun = $expression->getNextRunDate();
    
    • Pass a DateTimeZone to handle timezone-specific scheduling.
  3. Integration with Laravel Scheduler

    // In a custom scheduler command
    $schedule = CronExpression::factory('0 3 * * *');
    if ($schedule->isDue()) {
        // Execute task
    }
    
    • Useful for extending Laravel’s built-in scheduler logic.
  4. Recurring Tasks with Context

    $expression = CronExpression::factory('0 0 1 * *'); // First of every month
    $lastRun = new \DateTime('last month');
    $nextRun = $expression->getNextRunDate($lastRun);
    
    • Pass a DateTime to calculate runs relative to a specific point in time.

Advanced Patterns

  • Dynamic Cron Strings

    $userCron = $request->input('cron_expression');
    $expression = CronExpression::factory($userCron);
    
    • Validate and parse cron strings from APIs or forms.
  • Batch Processing

    $expressions = [
        CronExpression::factory('* * * * *'), // Every minute
        CronExpression::factory('*/5 * * * *'), // Every 5 minutes
    ];
    foreach ($expressions as $expr) {
        if ($expr->isDue()) {
            // Process
        }
    }
    
    • Manage multiple cron jobs in a single loop.
  • Logging and Metrics

    $expression = CronExpression::factory('0 * * * *');
    if ($expression->isDue()) {
        Log::info('Cron job triggered', ['expression' => $expression->getExpression()]);
    }
    
    • Track cron job executions for debugging or analytics.

Gotchas and Tips

Pitfalls

  1. Time Zone Mismatches

    • If not explicitly set, getNextRunDate() uses the server’s default timezone.
    • Fix: Always pass a DateTimeZone for consistency:
      $expression->getNextRunDate(new \DateTime('now', new \DateTimeZone('UTC')));
      
  2. Invalid Expressions

    • The package does not throw exceptions for invalid cron strings; isValid() returns false.
    • Fix: Validate before use:
      if (!$expression->isValid()) {
          throw new \InvalidArgumentException('Invalid cron expression');
      }
      
  3. Edge Cases in Date Calculation

    • getNextRunDate() may return dates in the past if called with a future DateTime.
    • Fix: Use getPreviousRunDate() or ensure the input DateTime is recent.
  4. Daylight Saving Time (DST) Quirks

    • Timezone transitions can cause unexpected shifts in getNextRunDate().
    • Fix: Test with edge-case timezones (e.g., America/New_York).

Debugging Tips

  • Inspect Parsed Components

    $expression = CronExpression::factory('0 0 * * 0'); // Sunday at midnight
    $fields = $expression->getFields(); // Array of parsed values
    
    • Useful for verifying cron syntax.
  • Log Cron Expressions

    Log::debug('Cron expression parsed as:', [
        'raw' => $expression->getExpression(),
        'fields' => $expression->getFields(),
    ]);
    

Extension Points

  1. Custom Field Parsing

    • Extend Cron\Field\FieldFactory to support non-standard cron syntax (e.g., @hourly).
  2. Integration with Laravel Events

    event(new CronJobTriggered($expression->getExpression()));
    
    • Dispatch events when cron conditions are met.
  3. Performance Optimization

    • Cache parsed expressions if used repeatedly:
      $cacheKey = 'cron:' . md5($expression->getExpression());
      $nextRun = Cache::remember($cacheKey, 60, function () use ($expression) {
          return $expression->getNextRunDate();
      });
      
  4. Testing

    • Use Mockery or PHPUnit to mock DateTime for predictable tests:
      $now = new \DateTime('2023-01-01 00:00:00');
      $expression->getNextRunDate($now);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui