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 Bundle Laravel Package

edgar/cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require edgar/cron-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Edgar\CronBundle\EdgarCronBundle::class => ['all' => true],
    ];
    
  2. Define a Cron Job Create a command extending AbstractCron (located in src/Command/):

    namespace App\Command;
    
    use Edgar\CronBundle\Command\AbstractCron;
    
    class MyCronJob extends AbstractCron
    {
        protected static $defaultName = 'app:my_cron_job';
        protected static $cron = '* * * * *'; // Default cron expression
        protected static $priority = 10; // Lower = higher priority
    
        protected function execute($input, $output)
        {
            // Your logic here
            $output->writeln('Running MyCronJob!');
        }
    }
    
  3. Tag the Command as a Service In config/services.yaml:

    services:
        App\Command\MyCronJob:
            tags: ['edgar.cron']
    
  4. Set Up the Cron Job Add this to your server’s crontab (replace <project_root>):

    * * * * * cd <project_root> && php bin/console edgar:crons:run
    
  5. Test Locally Run manually to verify:

    php bin/console edgar:crons:run
    

Implementation Patterns

Workflow Integration

  1. Command Organization Group cron jobs by domain (e.g., App\Command\Billing\, App\Command\Reports\) for clarity. Example:

    namespace App\Command\Reports;
    class GenerateMonthlyReport extends AbstractCron { ... }
    
  2. Dynamic Cron Expressions Override $cron per environment (e.g., dev vs. prod) using dependency injection:

    class MyCronJob extends AbstractCron
    {
        protected static $cron;
    
        public function __construct(string $cronExpression)
        {
            self::$cron = $cronExpression;
        }
    }
    

    Configure in config/services.yaml:

    services:
        App\Command\MyCronJob:
            arguments: ['%env(CRON_EXPRESSION)%']
            tags: ['edgar.cron']
    
  3. Priority Management Use priorities to control execution order (e.g., 0 for critical jobs, 100 for low-priority):

    protected static $priority = 5; // Mid-priority
    
  4. Logging and Monitoring Extend execute() to log output or integrate with Laravel’s logging:

    protected function execute($input, $output)
    {
        \Log::info('MyCronJob started');
        try {
            // Job logic
        } catch (\Exception $e) {
            \Log::error('MyCronJob failed: ' . $e->getMessage());
        }
    }
    
  5. Environment-Specific Jobs Disable jobs in certain environments by checking $this->getEnvironment():

    protected function execute($input, $output)
    {
        if ($this->getEnvironment() !== 'production') {
            return;
        }
        // Production logic
    }
    

Gotchas and Tips

Pitfalls

  1. Cron Expression Syntax

    • Invalid expressions (e.g., * * * * * *) will silently fail. Validate with tools like crontab.guru.
    • Example of a valid expression:
      protected static $cron = '0 0 * * 0'; // Weekly on Sunday at midnight
      
  2. Service Tagging

    • Forgetting to tag a command with edgar.cron will make it invisible to the scheduler.
    • Verify tags with:
      php bin/console debug:container edgar.cron
      
  3. Priority Collisions

    • Jobs with the same priority may execute in an undefined order. Use unique priorities (e.g., 1, 2, 3) for critical sequences.
  4. Time Zone Issues

    • Cron expressions use the server’s time zone. Ensure consistency with Laravel’s APP_TIMEZONE in .env:
      APP_TIMEZONE=UTC
      
  5. Debugging Execution

    • Add debug output to execute() to trace issues:
      $output->writeln('Debug: ' . print_r($this->getArguments(), true));
      
    • Check logs for errors:
      tail -f storage/logs/laravel.log
      

Tips

  1. Dry Runs Use --dry-run to list jobs without executing:

    php bin/console edgar:crons:run --dry-run
    
  2. Custom Scheduling Logic Override shouldRun() to add conditions:

    protected function shouldRun(): bool
    {
        return parent::shouldRun() && $this->isWeekend();
    }
    
    private function isWeekend(): bool
    {
        return date('N') >= 6; // Saturday (6) or Sunday (7)
    }
    
  3. Dependency Injection Inject services (e.g., repositories) into cron jobs:

    class MyCronJob extends AbstractCron
    {
        private $repository;
    
        public function __construct(MyRepository $repository)
        {
            $this->repository = $repository;
        }
    }
    
  4. Testing Cron Jobs Mock the edgar:crons:run command in PHPUnit:

    $this->artisan('edgar:crons:run')
         ->expectsQuestion('Run all crons?', 'yes')
         ->assertExitCode(0);
    
  5. Performance Considerations

    • Offload heavy tasks to queues (e.g., Laravel Queues) to avoid blocking the cron process.
    • Limit job runtime by setting a timeout in php.ini or via set_time_limit():
      set_time_limit(300); // 5 minutes
      
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui