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 Manager Bundle Laravel Package

bcc/cron-manager-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require bcc/cron-manager-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Bcc\CronManagerBundle\BccCronManagerBundle::class => ['all' => true],
    ];
    
  2. Basic Setup

    • Run migrations to create the cron_job table:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
    • Clear cache:
      php bin/console cache:clear
      
  3. First Use Case: Define a Cron Job Create a command (e.g., SendDailyNewsletterCommand) and register it in services.yaml:

    services:
        App\Command\SendDailyNewsletterCommand:
            tags: ['console.command']
    

    Then, use the bundle’s admin interface (accessible at /admin/cron) to schedule it:

    • Command: app:send-daily-newsletter
    • Schedule: 0 8 * * * (daily at 8 AM)
    • Active: ✅

Implementation Patterns

Workflow: Managing Cron Jobs

  1. Via Admin UI

    • Use the built-in dashboard (/admin/cron) to:
      • Add/edit/delete jobs.
      • Toggle active/inactive status.
      • View logs and execution history.
    • Ideal for non-developers or quick adjustments.
  2. Via Code (Programmatic Control) Use the CronManager service to interact with jobs programmatically:

    // Get the manager
    $cronManager = $this->container->get('bcc_cron_manager.cron_manager');
    
    // Create a job
    $job = new CronJob();
    $job->setCommand('app:send-daily-newsletter');
    $job->setSchedule('0 8 * * *');
    $job->setActive(true);
    $cronManager->save($job);
    
    // List all jobs
    $jobs = $cronManager->findAll();
    
  3. Integration with Symfony Events Listen for job-related events (e.g., bcc_cron_manager.job.run or bcc_cron_manager.job.failed) to extend functionality:

    # config/services.yaml
    services:
        App\EventListener\CronJobListener:
            tags:
                - { name: kernel.event_listener, event: bcc_cron_manager.job.run, method: onJobRun }
    
  4. Logging and Monitoring

    • Enable logging in config/packages/bcc_cron_manager.yaml:
      bcc_cron_manager:
          logging: true
      
    • View logs in Symfony’s profiler or via monolog channels.
  5. Environment-Specific Scheduling Use parameters to define schedules per environment (e.g., dev vs. prod):

    # config/packages/dev/bcc_cron_manager.yaml
    bcc_cron_manager:
        schedules:
            'app:send-daily-newsletter': '*/5 * * * *'  # Every 5 minutes in dev
    

Gotchas and Tips

Pitfalls

  1. Permissions Issues

    • Ensure the Symfony user (e.g., www-data) has permissions to execute commands.
    • Debug with:
      sudo -u www-data php bin/console app:your-command
      
  2. Cron Expression Syntax

    • The bundle uses cron expressions. Test expressions with tools like crontab.guru.
    • Common mistake: Forgetting to escape special characters in schedules (e.g., * * * * * ? for Quartz-style).
  3. Database Locking

    • Concurrent job executions may cause race conditions. Use transactions or locks in commands:
      $entityManager = $this->getDoctrine()->getManager();
      $entityManager->beginTransaction();
      try {
          // Job logic
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      
  4. Admin UI Access

    • The /admin/cron route is not secured by default. Protect it with Symfony’s security:
      # config/packages/security.yaml
      access_control:
          - { path: ^/admin/cron, roles: ROLE_ADMIN }
      
  5. Command Output Handling

    • By default, command output is logged to the Symfony log. For verbose output, redirect to a file:
      bcc_cron_manager:
          log_file: '%kernel.logs_dir%/cron_jobs.log'
      

Tips

  1. Custom Job Metadata Extend the CronJob entity to store additional fields (e.g., priority, last_run_at):

    // src/Entity/CustomCronJob.php
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class CustomCronJob extends CronJob {
        #[ORM\Column(type: 'integer')]
        private $priority = 1;
    }
    
  2. Dynamic Schedules Use Twig or PHP to generate schedules dynamically (e.g., based on user input):

    {# templates/admin/cron/new.html.twig #}
    <input type="text" name="schedule" value="{{ cronExpression(user.timezone) }}">
    
  3. Testing Cron Jobs Mock the CronManager in tests:

    $cronManager = $this->createMock(CronManager::class);
    $cronManager->method('findAll')->willReturn([$mockJob]);
    $this->container->set('bcc_cron_manager.cron_manager', $cronManager);
    
  4. Performance Optimization

    • For large-scale systems, use a queue (e.g., Symfony Messenger) instead of direct command execution.
    • Disable logging in production if not needed:
      bcc_cron_manager:
          logging: '%kernel.debug%'
      
  5. Backup and Migration

    • Regularly back up the cron_job table, as it’s critical for job persistence.
    • Use Doctrine migrations for schema changes:
      php bin/console make:migration
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware