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

durimjusaj/cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cron/cron-bundle
    

    Add to config/bundles.php (Symfony 5+):

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

    php bin/console make:migration
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Define a job via annotation or YAML:

    // src/Command/MyCronJob.php
    use Cron\CronBundle\Annotation\Cron;
    
    class MyCronJob {
        /**
         * @Cron("0 0 * * *")
         */
        public function run() {
            // Your logic here
        }
    }
    

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

    cron:
        jobs:
            my_job:
                class: App\Command\MyCronJob
                method: run
                schedule: "0 0 * * *"
    
  4. Test Locally:

    php bin/console cron:list  # Verify jobs
    php bin/console cron:run  # Execute manually
    

Implementation Patterns

Core Workflows

  1. Job Definition:

    • Annotations: Decorate methods with @Cron("schedule") (e.g., @Cron("*/5 * * * *") for every 5 minutes).
    • YAML/Config: Centralize schedules in config/packages/cron.yaml for maintainability:
      cron:
          jobs:
              cleanup:
                  class: App\Command\CleanupCommand
                  method: execute
                  schedule: "0 0 3 * *"  # Daily at 3 AM
                  timezone: "Europe/Berlin"
      
  2. Execution:

    • Manual Trigger: php bin/console cron:run [job_name] (e.g., php bin/console cron:run cleanup).
    • Automated: Add to crontab (Linux/macOS):
      * * * * * cd /path/to/project && php bin/console cron:run >> /dev/null 2>&1
      
      Or use Systemd Timer (Symfony 5+):
      # /etc/systemd/system/cron-jobs.timer
      [Unit]
      Description=Run Symfony cron jobs
      
      [Timer]
      OnCalendar=*-*-* *:0/5  # Every 5 minutes
      Persistent=true
      
      [Install]
      WantedBy=timers.target
      
  3. Logging & Monitoring:

    • Enable logging in config/packages/cron.yaml:
      cron:
          logging: true
      
    • Check logs via php bin/console cron:log or Symfony’s default logger.
  4. Dependency Injection:

    • Inject services into cron jobs:
      class MyJob {
          public function __construct(private MailerInterface $mailer) {}
      
          #[Cron("0 0 12 * *")]
          public function sendDailyReport() {
              $this->mailer->send(...);
          }
      }
      
  5. Environment-Specific Schedules:

    • Use %env% in schedules (Symfony 5+):
      cron:
          jobs:
              deploy_check:
                  schedule: "%env(DEPLOY_CHECK_CRON)%"  # e.g., "*/10 * * * *"
      

Integration Tips

  1. Laravel-Specific Adaptations:

    • Replace AppKernel with config/bundles.php (Symfony 5+).
    • Use Laravel’s Artisan facade to trigger jobs:
      Artisan::call('cron:run', ['job' => 'my_job']);
      
    • For Laravel’s scheduler, combine with laravel-scheduler package for hybrid setups.
  2. Queue Integration:

    • Dispatch jobs to queues for async execution:
      #[Cron("0 * * * *")]
      public function asyncTask() {
          dispatch(new ProcessAsyncTask());
      }
      
  3. Testing:

    • Mock the CronManager in PHPUnit:
      $this->cronManager = $this->createMock(CronManager::class);
      $this->cronManager->expects($this->once())
          ->method('runJob')
          ->with('my_job');
      

Gotchas and Tips

Pitfalls

  1. Timezone Mismatches:

    • Cron schedules default to UTC. Explicitly set timezones in config:
      cron:
          timezone: "America/New_York"
      
    • Debug with php bin/console cron:list --verbose to confirm timezone.
  2. Database Locking:

    • The bundle uses a cron_job table to track runs. Ensure your DB supports transactions to avoid race conditions during migrations.
  3. Crontab Permissions:

    • Ensure the cron user has execute permissions for bin/console:
      chmod +x bin/console
      
    • Test manually before adding to crontab:
      sudo -u www-data php bin/console cron:run
      
  4. Job Overlaps:

    • By default, jobs run sequentially. For parallel execution, use Symfony’s Messenger component or Laravel Queues.
  5. Annotation vs. YAML:

    • Annotations are not processed by Symfony’s autowiring by default. Ensure your services.yaml includes:
      services:
          _defaults:
              autowire: true
              autoconfigure: true
          App\:
              resource: '../src/'
              excludes: ['../src/{Kernel.php,Tests}']
      

Debugging

  1. Logs:

    • Enable debug mode in config/packages/cron.yaml:
      cron:
          debug: true
      
    • Check var/log/dev.log for execution details.
  2. Dry Runs:

    • Test schedules without execution:
      php bin/console cron:list --next-run
      
  3. Common Errors:

    • "Job not found": Verify the job is registered in cron.yaml and the class/method exists.
    • Permission denied: Ensure the cron user has access to project files and PHP CLI.
    • Timezone issues: Use date in your terminal to confirm the server’s timezone:
      date +"%Z %z"
      

Extension Points

  1. Custom Job Storage:

    • Override the default CronJobRepository to use a custom storage backend (e.g., Redis):
      // src/Cron/CustomJobRepository.php
      class CustomJobRepository extends DoctrineJobRepository {
          public function __construct(Connection $connection, string $table = 'custom_cron_jobs') {
              parent::__construct($connection, $table);
          }
      }
      
      Register in config/services.yaml:
      services:
          Cron\CronBundle\Repository\CronJobRepository:
              class: App\Cron\CustomJobRepository
      
  2. Pre/Post Hooks:

    • Extend the CronJob entity to add lifecycle callbacks:
      #[ORM\Entity]
      class CronJob extends BaseCronJob {
          #[PrePersist]
          public function setCreatedAt(): void {
              $this->createdAt = new \DateTime();
          }
      }
      
  3. Dynamic Schedules:

    • Fetch schedules from an API or database:
      #[Cron("0 0 * * *")]
      public function updateDynamicJobs() {
          $schedules = $this->scheduleRepository->findAll();
          foreach ($schedules as $schedule) {
              $this->cronManager->addJob($schedule->getName(), $schedule->getClass(), [
                  'method' => $schedule->getMethod(),
                  'schedule' => $schedule->getCronExpression(),
              ]);
          }
          $this->cronManager->saveJobs();
      }
      
  4. Event Listeners:

    • Listen to job events (e.g., CronJobRunEvent):
      // src/EventListener/CronListener.php
      class CronListener implements EventSubscriberInterface {
          public static function getSubscribedEvents(): array {
              return [
                  CronJobRunEvent::NAME => 'onJobRun',
              ];
          }
      
          public function onJobRun(CronJobRunEvent $event): void {
              // Log or modify job execution
          }
      }
      
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