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

effiana/cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require effiana/cron-bundle
    

    Add to config/bundles.php:

    Effiana\CronBundle\EffianaCronBundle::class => ['all' => true],
    
  2. Database Migration:

    bin/console effiana:migration:load --force
    

    (Alternative: Use make:migration + doctrine:migrations:migrate if preferred.)

  3. First Use Case: Define a job via annotation in a service:

    use Effiana\CronBundle\Annotation\Cron;
    
    class MyJobService
    {
        /**
         * @Cron("0 0 * * *", name="daily_report")
         */
        public function generateDailyReport()
        {
            // Job logic here
        }
    }
    

    Verify jobs are registered:

    bin/console cron:list
    
  4. Manual Execution:

    bin/console cron:run
    

Implementation Patterns

Core Workflows

  1. Job Definition:

    • Annotations: Decorate methods with @Cron("schedule", name="job_name").
    • YAML/XML: Define jobs in config/cron.yml (if supported; check docs).
    • Programmatic: Register jobs via CronManager in a service:
      $manager->addJob(new MyJob(), '0 * * * *');
      
  2. Execution:

    • Manual: Run via CLI (cron:run).
    • Automated:
      • Cron Daemon: Add to crontab (Linux):
        * * * * * /path/to/php /path/to/app/console cron:run >> /dev/null 2>&1
        
      • Heroku/No Cron: Use cron:start (if supported) or a worker process.
  3. Logging & Monitoring:

    • Check job logs via cron:list or Symfony’s monolog.
    • Extend JobInterface to add custom logging:
      class MyJob implements JobInterface {
          public function run() {
              // ...
              $this->logger->info('Job executed');
          }
      }
      
  4. Dependency Injection:

    • Inject services into jobs via constructor:
      class MyJob implements JobInterface {
          private $mailer;
      
          public function __construct(\Swift_Mailer $mailer) {
              $this->mailer = $mailer;
          }
      }
      

Integration Tips

  • Laravel-Specific:

    • Use Laravel’s Artisan facade to trigger jobs:
      \Artisan::call('cron:run');
      
    • Bind the CronManager to Laravel’s container in AppServiceProvider:
      $this->app->bind('effiana.cron.manager', function ($app) {
          return new \Effiana\CronBundle\Manager\CronManager();
      });
      
  • Queue Integration:

    • Dispatch jobs to Laravel queues for async execution:
      \Queue::push(new MyJob());
      
    • Modify JobInterface::run() to use Laravel’s queue system.
  • Event Listeners:

    • Trigger events before/after job execution:
      $dispatcher->addListener('cron.job.before', function ($job) {
          // Pre-job logic
      });
      

Gotchas and Tips

Pitfalls

  1. Database Schema:

    • The bundle creates tables for job logs. Ensure migrations run successfully.
    • Fix: If migrations fail, drop tables manually or use --force flag.
  2. Cron Syntax:

    • The bundle uses standard cron syntax (* * * * *). Test schedules with crontab.guru.
    • Gotcha: Off-by-one errors in minute/hour fields (e.g., 0 0 * * * = midnight daily).
  3. Timezone Issues:

    • Cron schedules run in the server’s timezone. Explicitly set timezone in config.php:
      'timezone' => 'UTC',
      
  4. Job Isolation:

    • Jobs run in the same process. Long-running jobs may block others.
    • Solution: Use Laravel’s queues or split jobs into smaller tasks.
  5. Annotation Parsing:

    • Annotations must be parsed by Doctrine’s annotation reader. Ensure doctrine/annotations is installed:
      composer require doctrine/annotations
      

Debugging

  • Job Not Running?:

    • Check if the job is registered:
      bin/console cron:list
      
    • Verify cron syntax and permissions for the cron user.
    • Enable debug mode in config.php:
      'debug' => true,
      
  • Logs:

    • Job execution logs are stored in the database. Query cron_job_logs table:
      SELECT * FROM cron_job_logs ORDER BY created_at DESC;
      
    • Enable Symfony’s monolog for additional logs.

Extension Points

  1. Custom Job Storage:

    • Override the default JobRepository to use a custom storage backend (e.g., Redis):
      $manager->setJobRepository(new RedisJobRepository());
      
  2. Job Events:

    • Extend the bundle’s event system:
      $dispatcher->addListener('cron.job.after', function ($job, $result) {
          // Post-job logic
      });
      
  3. Command Customization:

    • Override the cron:run command in a custom bundle:
      class CustomCronCommand extends CronCommand {
          protected function execute(InputInterface $input, OutputInterface $output) {
              // Custom logic
              parent::execute($input, $output);
          }
      }
      
  4. Laravel-Specific Extensions:

    • Create a Laravel command to wrap the bundle’s functionality:
      // app/Console/Commands/RunCronJobs.php
      class RunCronJobs extends Command {
          public function handle() {
              \Artisan::call('cron:run');
          }
      }
      

Tips

  • Idempotency:

    • Design jobs to be idempotent (safe to rerun). Use database locks or flags to avoid duplicate work.
  • Environment-Specific Schedules:

    • Define schedules per environment in config/cron.php:
      'schedules' => [
          'development' => ['0 * * * *' => ['job1', 'job2']],
          'production'  => ['0 0 * * *' => ['job1']],
      ],
      
  • Testing:

    • Mock the CronManager in PHPUnit:
      $mockManager = $this->createMock(CronManager::class);
      $mockManager->expects($this->once())->method('runJob');
      $this->app->instance('effiana.cron.manager', $mockManager);
      
  • Performance:

    • Batch jobs if processing large datasets:
      $batchSize = 100;
      for ($i = 0; $i < $totalItems; $i += $batchSize) {
          $this->processBatch($i, $batchSize);
      }
      
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope