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

Cronos Laravel Package

mybuilder/cronos

Cronos is a Laravel-friendly task scheduling package for defining, running, and monitoring cron-style jobs from your app. Organize recurring tasks, trigger them on demand, and manage schedules with a clean API and sensible defaults.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mybuilder/cronos
    

    Add to composer.json if not using Composer:

    "require": {
        "mybuilder/cronos": "^1.0"
    }
    
  2. Basic Usage

    use Cronos\CronExpression;
    
    $expression = CronExpression::factory('* * * * *'); // Every minute
    $nextRun = $expression->getNextRunDate(); // Get next execution time
    
  3. First Use Case Validate a cron expression in a Laravel request:

    use Cronos\CronExpression;
    use Illuminate\Http\Request;
    
    public function validateCron(Request $request)
    {
        $expression = $request->input('cron_expression');
        $isValid = CronExpression::isValidExpression($expression);
    
        return response()->json(['valid' => $isValid]);
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Cron Validation

    public function storeCronJob(Request $request)
    {
        $expression = $request->input('cron_expression');
        $cron = CronExpression::factory($expression);
    
        if (!$cron->isValid()) {
            return back()->withErrors(['cron_expression' => 'Invalid cron syntax']);
        }
    
        // Save to DB or process further
    }
    
  2. Next Run Calculation

    public function getNextRun(DateTime $currentTime = null)
    {
        $cron = CronExpression::factory('0 12 * * 1'); // Every Monday at noon
        $nextRun = $cron->getNextRunDate($currentTime ?? now());
    
        return $nextRun->format('Y-m-d H:i:s');
    }
    
  3. Timezone Handling

    $cron = CronExpression::factory('* * * * *', 'America/New_York');
    $nextRun = $cron->getNextRunDate();
    

Integration Tips

  • Laravel Scheduler: Use with Artisan::schedule() for dynamic cron jobs:
    $schedule->command('my:command')->cron(CronExpression::factory('* * * * *')->getExpression());
    
  • Form Validation: Extend Laravel’s Cron rule:
    use Cronos\CronExpression;
    use Illuminate\Validation\Rule;
    
    $rules = [
        'cron_expression' => [
            'required',
            function ($attribute, $value, $fail) {
                if (!CronExpression::isValidExpression($value)) {
                    $fail('The '.$attribute.' format is invalid.');
                }
            }
        ]
    ];
    
  • API Responses: Serialize cron data for APIs:
    return response()->json([
        'expression' => $cron->getExpression(),
        'next_run' => $cron->getNextRunDate()->toIso8601String(),
        'timezone' => $cron->getTimezone()->getName(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Timezone Ambiguity

    • Cronos defaults to UTC. Always explicitly set timezones for local cron jobs:
      $cron = CronExpression::factory('* * * * *', 'Europe/London');
      
    • Debug timezone issues with:
      $cron->getTimezone()->getName(); // Verify timezone
      
  2. Edge Cases in Validation

    • CronExpression::isValidExpression() may return true for syntactically correct but logically invalid expressions (e.g., * * * * * *).
    • Validate field counts manually if needed:
      $parts = explode(' ', $expression);
      if (count($parts) !== 5 && count($parts) !== 6) {
          return false;
      }
      
  3. DateTime Precision

    • getNextRunDate() returns a DateTime object. Ensure your Laravel models/DB fields handle microseconds if needed:
      $nextRun = $cron->getNextRunDate()->setTimezone('UTC');
      

Debugging

  • Log Cron Expressions Use TALL stack logging to inspect cron parsing:
    \Log::debug('Cron expression:', [
        'raw' => $expression,
        'parsed' => CronExpression::factory($expression)->getParts(),
    ]);
    
  • Test with now() Pass a fixed DateTime to isolate time-related bugs:
    $fixedTime = new DateTime('2023-01-01 00:00:00');
    $nextRun = $cron->getNextRunDate($fixedTime);
    

Extension Points

  1. Custom Parsing Extend Cronos\CronExpression for non-standard formats (e.g., @hourly):

    if (str_starts_with($expression, '@')) {
        return match ($expression) {
            '@hourly' => '* * * * *',
            '@daily' => '0 0 * * *',
            // ...
            default => throw new \InvalidArgumentException('Unknown shorthand'),
        };
    }
    
  2. Laravel Service Provider Bind Cronos to the container for global access:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(CronExpression::class, function () {
            return CronExpression::factory('* * * * *');
        });
    }
    
  3. Database Storage Store cron expressions as strings in DB, but validate on retrieval:

    $job = Job::find($id);
    $cron = CronExpression::factory($job->cron_expression);
    if (!$cron->isValid()) {
        $job->forceFill(['cron_expression' => '* * * * *'])->save();
    }
    

Performance

  • Caching Parsed Expressions Cache validated cron expressions to avoid reprocessing:
    $cacheKey = 'cron:'.$expression;
    $cron = Cache::remember($cacheKey, now()->addHours(1), function () use ($expression) {
        return CronExpression::factory($expression);
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky