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

cron/cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require cron/cron-bundle
    

    Register the bundle in config/bundles.php (Symfony 4.3+):

    return [
        // ...
        Cron\CronBundle\CronCronBundle::class => ['all' => true],
    ];
    
  2. Database Setup:

    php artisan make:migration CreateCronJobsTable --table=cron_jobs
    

    Run migrations:

    php artisan migrate
    
  3. First Use Case: Define a job in a service class (e.g., app/Services/MyCronJob.php):

    namespace App\Services;
    
    use Cron\CronBundle\Job\JobInterface;
    
    class MyCronJob implements JobInterface
    {
        public function run()
        {
            // Your logic here (e.g., send emails, clean cache)
            \Log::info('My cron job executed!');
        }
    }
    

    Register the job in config/packages/cron.yaml:

    cron:
        jobs:
            my_job:
                class: App\Services\MyCronJob
                schedule: "*/5 * * * *"  # Every 5 minutes
                enabled: true
    
  4. Test Manually:

    php artisan cron:list       # List all jobs
    php artisan cron:run       # Run all enabled jobs once
    php artisan cron:run my_job # Run a specific job
    

Implementation Patterns

Core Workflows

  1. Job Definition:

    • Service-Based: Implement JobInterface in a service class (recommended for reusability).
      class CleanupJob implements JobInterface {
          public function run() {
              // Business logic
          }
      }
      
    • Closure-Based: Use anonymous functions for simple tasks (avoid for complex logic).
      cron:
          jobs:
              simple_job:
                  on:  # Alternative to schedule (runs on demand)
                  run: |
                      \Log::info('Simple job ran!');
      
  2. Scheduling:

    • Use crontab syntax in config/packages/cron.yaml:
      schedule: "0 0 * * *"  # Daily at midnight
      
    • Leverage Symfony’s on option for event-driven triggers:
      on:
          command: "app:event-trigger"
          event: "app.some_event"
      
  3. Integration with Laravel:

    • Service Providers: Bind jobs to the container in AppServiceProvider:
      $this->app->bind('App\Jobs\MyJob', function () {
          return new MyJob();
      });
      
    • Task Scheduling: Use Laravel’s schedule:run in a cron entry (wrap the bundle’s command):
      * * * * * cd /path-to-project && php artisan schedule:run >> /dev/null 2>&1
      
      Then define a scheduled job in app/Console/Kernel.php:
      protected function schedule(Schedule $schedule) {
          $schedule->command('cron:run')->everyMinute();
      }
      
  4. Logging and Monitoring:

    • Enable logging in config/packages/cron.yaml:
      logging: true
      
    • Check logs with:
      php artisan cron:log
      

Gotchas and Tips

Pitfalls

  1. Database Locking:

    • The bundle uses database locks to prevent overlapping runs. If jobs hang, check for:
      • Long-running queries in run().
      • Missing release() calls (though JobInterface auto-handles this).
    • Fix: Add a timeout to your cron entry (e.g., */5 * * * * timeout 300 php artisan cron:run).
  2. Timezone Mismatches:

    • Cron schedules use the server’s timezone. Ensure consistency:
      # config/packages/cron.yaml
      timezone: "Europe/Paris"
      
    • Debug with:
      php artisan cron:list --verbose
      
  3. Dependency Injection:

    • Avoid hardcoding services in jobs. Use constructor injection:
      class MyJob implements JobInterface {
          private $logger;
      
          public function __construct(\Psr\Log\LoggerInterface $logger) {
              $this->logger = $logger;
          }
      
          public function run() {
              $this->logger->info('Job running');
          }
      }
      
    • Gotcha: The bundle’s DI container may not resolve Laravel’s App facade directly. Use interfaces (e.g., LoggerInterface).
  4. Migration Conflicts:

    • If you manually edit the cron_jobs table, run:
      php artisan cron:migrate
      
      to reset schema changes.

Debugging Tips

  1. Dry Runs:

    • Test schedules without executing:
      php artisan cron:list --dry-run
      
  2. Job Isolation:

    • Run a single job in debug mode:
      php artisan cron:run my_job --env=local --verbose
      
  3. Environment-Specific Jobs:

    • Use enabled flag to toggle jobs per environment:
      cron:
          jobs:
              production_only_job:
                  schedule: "0 3 * * *"
                  enabled: "%kernel.environment% == 'prod'"
      

Extension Points

  1. Custom Job Storage:

    • Override the default Doctrine ORM storage by implementing Cron\CronBundle\Storage\StorageInterface and configuring in cron.yaml:
      storage:
          class: App\Storage\CustomCronStorage
      
  2. Event Listeners:

    • Hook into job lifecycle events (e.g., JobBeforeRunEvent):
      // src/EventListener/CronListener.php
      use Cron\CronBundle\Event\JobBeforeRunEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class CronListener implements EventSubscriberInterface {
          public static function getSubscribedEvents() {
              return [
                  JobBeforeRunEvent::NAME => 'onJobBeforeRun',
              ];
          }
      
          public function onJobBeforeRun(JobBeforeRunEvent $event) {
              if ($event->getJob()->getName() === 'my_job') {
                  $event->stopPropagation(); // Skip execution
              }
          }
      }
      
  3. Parallel Execution:

    • Use Symfony’s Messenger component to run jobs asynchronously:
      cron:
          jobs:
              async_job:
                  class: App\Services\AsyncJob
                  schedule: "*/10 * * * *"
                  messenger: true  # Offloads to messenger queue
      
    • Requires symfony/messenger and configuration in config/packages/messenger.yaml.
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
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