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

Cronbundle Laravel Package

alpixel/cronbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require alpixel/cronbundle:^2.0
    

    Register the bundle in AppKernel.php:

    new Alpixel\Bundle\CronBundle\CronBundle(),
    
  2. Database Setup Run migrations or schema update:

    php app/console doctrine:migrations:diff
    php app/console doctrine:migrations:migrate
    

    or

    php app/console doctrine:schema:update --force
    
  3. First Use Case: Create a Cron Job Create a Symfony Command class and annotate it with @CronJob:

    use Alpixel\Bundle\CronBundle\Annotation\CronJob;
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    /**
     * @CronJob(value="PT1H", startTime="today 12:00")
     */
    class MyCronCommand extends Command
    {
        protected function configure()
        {
            $this->setName('app:my-cron-job');
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $output->writeln('Running every hour!');
        }
    }
    
  4. Scan and Run Scan for new cron jobs:

    php app/console cron:scan
    

    Run the cron jobs:

    php app/console cron:run
    
  5. Server-Side Cron Setup Add a cron entry on your server (e.g., every 5 minutes):

    */5 * * * * /usr/bin/php /path/to/app/console cron:run --env=prod
    

Implementation Patterns

Workflows

  1. Developing New Cron Jobs

    • Extend Symfony\Component\Console\Command\Command or Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.
    • Annotate with @CronJob(value="PT1H", startTime="today 12:00") to define frequency and initial run time.
    • Use DateInterval format for value (e.g., PT1H for hourly, P1D for daily).
    • Run cron:scan after adding new jobs to register them in the database.
  2. Integrating with Existing Commands

    • Reuse existing commands by tagging them with @CronJob without modifying their logic.
    • Example:
      /**
       * @CronJob(value="P1D")
       */
      class ExistingCommand extends Command { ... }
      
  3. Dynamic Configuration

    • Use dependency injection to fetch configuration from services or environment variables.
    • Example:
      class DynamicCronCommand extends Command
      {
          private $config;
      
          public function __construct($config)
          {
              $this->config = $config;
          }
      
          protected function execute(InputInterface $input, OutputInterface $output)
          {
              $output->writeln('Running with config: ' . $this->config);
          }
      }
      
  4. Logging and Monitoring

    • Log cron job execution in execute() for debugging:
      $this->getHelper('dialog')->write('Cron job executed at ' . date('Y-m-d H:i:s'));
      
    • Use Symfony’s logger service for structured logs:
      $logger = $this->getContainer()->get('logger');
      $logger->info('Cron job executed', ['command' => $this->getName()]);
      
  5. Environment-Specific Jobs

    • Use --env flag in cron setup to run jobs in specific environments (e.g., prod).
    • Example cron entry:
      */10 * * * * /usr/bin/php /path/to/app/console cron:run --env=prod
      

Integration Tips

  • Database-Driven Scheduling: Cron jobs are stored in the database, allowing dynamic updates without code changes.
  • Symfony Services: Access services (e.g., Doctrine, Mailer) via ContainerAwareCommand or dependency injection.
  • Testing: Mock cron jobs in tests by directly calling execute() or using cron:run with --dry-run.
  • Error Handling: Wrap critical logic in try-catch blocks and log errors:
    try {
        // Risky operations
    } catch (\Exception $e) {
        $this->getLogger()->error('Cron job failed', ['error' => $e->getMessage()]);
    }
    

Gotchas and Tips

Pitfalls

  1. CLI Environment Limitations

    • Cron jobs run in CLI mode, so web-specific services (e.g., Request, Router) are unavailable.
    • Workaround: Use services like Mailer or EntityManager directly or configure them for CLI.
    • Example for URLs:
      $urlGenerator = $this->getContainer()->get('router')->getContext()->getSchemeAndHttpHost();
      
  2. Time Zone Issues

    • startTime uses the server’s time zone. Ensure consistency with your application’s time zone.
    • Fix: Set date.timezone in php.ini or use DateTime with explicit time zones:
      $startTime = new \DateTime('today 12:00', new \DateTimeZone('Europe/Paris'));
      
  3. Database Locking

    • Concurrent cron:run executions may cause race conditions if not handled.
    • Solution: Use database transactions or locks:
      $entityManager = $this->getContainer()->get('doctrine')->getManager();
      $entityManager->beginTransaction();
      try {
          // Critical operations
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      
  4. Cron Job Overlaps

    • Jobs with short intervals (e.g., PT5M) may overlap if execution time exceeds the interval.
    • Mitigation: Add logging to track execution duration and adjust intervals.
  5. Annotation Caching

    • After adding @CronJob, run cron:scan to update the database. Forgetting this step causes jobs to appear "missing."
    • Tip: Clear cache if annotations aren’t detected:
      php app/console cache:clear
      

Debugging

  1. Dry Runs Use --dry-run to simulate cron execution without modifying the database:

    php app/console cron:run --dry-run
    
  2. Logging Enable debug mode to log cron job scans and executions:

    php app/console cron:scan -v
    php app/console cron:run -vv
    
  3. Database Inspection Check the cron_job table for registered jobs:

    SELECT * FROM cron_job;
    
    • Verify next_run_at and interval values match expectations.
  4. Command-Line Arguments Pass arguments to cron jobs via execute() or use setArguments() in tests:

    $command = new MyCronCommand();
    $command->setArguments(['--option' => 'value']);
    $command->run(new ArrayInput([]), new BufferedOutput());
    

Extension Points

  1. Custom Storage Override the default Doctrine storage by implementing Alpixel\Bundle\CronBundle\Model\CronJobInterface and configuring a custom repository.

  2. Event Listeners Subscribe to cron job events (e.g., cron.job.before, cron.job.after) via Symfony’s event dispatcher:

    $dispatcher->addListener('cron.job.before', function ($event) {
        // Pre-execution logic
    });
    
  3. Dynamic Intervals Modify intervals at runtime by updating the cron_job table or using a service to fetch dynamic values:

    $interval = $this->getContainer()->get('my_service')->getDynamicInterval();
    $cronJob->setInterval($interval);
    
  4. Parallel Execution For long-running jobs, consider splitting tasks or using a queue system (e.g., Symfony Messenger) to avoid blocking the cron process.

  5. Environment Variables Load cron job configurations from environment variables (e.g., .env):

    $interval = getenv('CRON_JOB_INTERVAL') ?: 'PT1H';
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon