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

Symfony Cron Bundle Laravel Package

course-hero/symfony-cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require course-hero/symfony-cron-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        SymfonyCronBundle\SymfonyCronBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration (in config/packages/symfony_cron.yaml):

    symfony_cron:
        lock_service: SymfonyCronBundle\Component\Lock\LockFileService
        process_service: SymfonyCronBundle\Component\Process\ProcessService
    
  3. First Use Case: Create a command to run via cron:

    php bin/console make:command DailyReport
    

    Then configure it in config/cron.yml (or via YAML/annotation):

    commands:
        app:daily-report:
            schedule: "0 0 * * *"  # Runs daily at midnight
            lock_service: "@symfony_cron.lock_file_service"
    

Implementation Patterns

Workflows

  1. Locking Strategies:

    • Use LockFileService for simple file-based locks (default).
    • Replace with MemcachedLockService or RedisLockService for distributed environments:
      services:
          symfony_cron.lock_memcached_service:
              class: SymfonyCronBundle\Component\Lock\MemcachedLockService
              arguments: ["@memcached.client"]
      
  2. Process Isolation:

    • Always wrap cron jobs in ProcessService to avoid orphaned locks:
      use SymfonyCronBundle\Component\Process\ProcessService;
      
      class DailyReportCommand extends Command {
          protected function execute(InputInterface $input, OutputInterface $output) {
              $processService = $this->get('symfony_cron.process_service');
              $processService->run(function() {
                  // Your job logic here
              });
          }
      }
      
  3. Dynamic Scheduling:

    • Use annotations for per-command schedules:
      use SymfonyCronBundle\Annotation\Cron;
      
      /**
       * @Cron(schedule="0 3 * * 1") // Every Monday at 3 AM
       */
      class WeeklyBackupCommand extends Command { ... }
      
  4. Event-Driven Triggers:

    • Combine with Symfony’s EventDispatcher for pre/post-execution hooks:
      services:
          app.cron.event_listener:
              class: App\EventListener\CronEventListener
              tags:
                  - { name: kernel.event_listener, event: cron.job.start, method: onJobStart }
      

Gotchas and Tips

Pitfalls

  1. Lock Timeouts:

    • Default lock TTL is 3600 seconds (1 hour). Adjust in config:
      symfony_cron:
          lock_ttl: 1800  # 30 minutes
      
    • Debugging: Check lock files in var/cron-locks/ (default path).
  2. Process Leaks:

    • If a job crashes, locks may linger. Use ProcessService mandatorily to fork processes:
      $processService->run(function() {
          // Job code here
      }, ['timeout' => 3600]); // Optional timeout
      
  3. Symfony 4+ Compatibility:

    • The bundle targets Symfony 2.5+. For Symfony 4/5:
      • Use autoconfigure: true in config/packages/framework.yaml.
      • Replace services.yml with config/services.yaml.
  4. Cron Expression Parsing:

    • Validate expressions with CronExpression class:
      use SymfonyCronBundle\Component\Cron\CronExpression;
      
      $expression = new CronExpression('0 0 * * *');
      if (!$expression->isValid()) {
          throw new \RuntimeException('Invalid cron expression');
      }
      

Tips

  1. Logging:

    • Enable cron job logging via Monolog:
      monolog:
          handlers:
              cron:
                  type: stream
                  path: "%kernel.logs_dir%/cron.log"
                  level: debug
      
  2. Testing:

    • Mock LockService and ProcessService in PHPUnit:
      $lockService = $this->createMock(LockServiceInterface::class);
      $lockService->method('lock')->willReturn(true);
      $this->container->set('symfony_cron.lock_file_service', $lockService);
      
  3. Custom Lock Backends:

    • Extend AbstractLockService for databases or custom storage:
      class DatabaseLockService extends AbstractLockService {
          protected function getLockKey($jobName) {
              return "cron_lock_{$jobName}";
          }
          // Implement lock/unlock logic
      }
      
  4. Environment-Specific Scheduling:

    • Use %kernel.environment% in cron expressions:
      commands:
          app:cleanup:
              schedule: "0 2 * * *"  # Prod only
              env: prod
      
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.
milito/query-filter
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