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

Command Scheduler Bundle Laravel Package

dukecity/command-scheduler-bundle

Symfony bundle to schedule console commands with cron expressions. Manage native and custom commands, backed by database storage and optional Doctrine migrations. Supports modern PHP/Symfony versions; see wiki for configuration, execution, and upgrade notes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer config extra.symfony.allow-contrib true
    composer require dukecity/command-scheduler-bundle
    
  2. Enable Contrib Recipes (if not already done).
  3. Run Migrations:
    php bin/console make:migration
    php bin/console doctrine:migrations:migrate
    
  4. Install Assets:
    php bin/console assets:install --symlink --relative public
    
  5. Secure the Route (add to config/packages/security.yaml):
    access_control:
        - { path: ^/command-scheduler, role: ROLE_ADMIN }
    

First Use Case

Schedule a command (e.g., app:send-emails) to run daily at midnight:

  1. Navigate to /command-scheduler/list.
  2. Click "New Schedule".
  3. Select the command from the dropdown.
  4. Enter 0 0 * * * in the Cron Expression field.
  5. Save the schedule.

Implementation Patterns

Core Workflow

  1. Define Commands: Ensure your Symfony console commands are registered (e.g., app:send-emails). The bundle auto-discovers them via Symfony’s CommandLoader.

  2. Schedule via UI: Use the /command-scheduler/list dashboard to:

    • Create schedules with cron expressions (e.g., */5 * * * * for every 5 minutes).
    • Enable/disable schedules.
    • Execute commands immediately via the "Run Now" button.
  3. Programmatic Scheduling (Advanced): Use the ScheduledCommandFactory service to create schedules programmatically:

    use Dukecity\CommandSchedulerBundle\Factory\ScheduledCommandFactory;
    
    public function __construct(private ScheduledCommandFactory $factory) {}
    
    public function scheduleExampleCommand(): void
    {
        $scheduledCommand = $this->factory->create();
        $scheduledCommand->setCommand('app:send-emails');
        $scheduledCommand->setCronExpression('0 0 * * *');
        $scheduledCommand->setEnabled(true);
        $entityManager->persist($scheduledCommand);
        $entityManager->flush();
    }
    
  4. Event-Driven Extensions: Listen to bundle events (e.g., SchedulerCommandExecutedEvent, SchedulerCommandFailedEvent) to log or notify:

    use Dukecity\CommandSchedulerBundle\Event\SchedulerCommandExecutedEvent;
    use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
    
    #[AsEventListener(event: SchedulerCommandExecutedEvent::class, method: 'onCommandExecuted')]
    public function onCommandExecuted(SchedulerCommandExecutedEvent $event): void
    {
        // Custom logic (e.g., Slack notification)
    }
    

Integration Tips

  1. Environment-Specific Scheduling: Use different cron expressions for dev vs. prod environments by overriding the bundle config:

    # config/packages/dukecity_command_scheduler.yaml
    dukecity_command_scheduler:
        cron_expressions:
            app:send-emails: "%env(CRON_EXPRESSION)%"  # e.g., "*/10 * * * *" in prod
    
  2. Custom Command Arguments: Pass arguments to scheduled commands via the arguments field in the UI or programmatically:

    $scheduledCommand->setArguments(['--limit=100']);
    
  3. Logging and Monitoring: Extend the BaseScheduledCommand entity to add custom fields (e.g., lastExecutionLog) for tracking:

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $lastExecutionLog = null;
    
  4. Testing: Use the SchedulerCommandTestTrait (if available) or mock the ScheduledCommandRepository in tests:

    $this->entityManager->remove($scheduledCommand);
    $this->entityManager->flush();
    

Gotchas and Tips

Pitfalls

  1. Cron Expression Syntax:

    • Invalid expressions (e.g., 0 0 * *) will throw errors. Validate with tools like crontab.guru.
    • The bundle uses Symfony’s CronExpression component, which may behave differently than Unix cron.
  2. Command Discovery:

    • Non-Symfony commands (e.g., custom PHP scripts) won’t appear in the dropdown. Ensure commands are registered as Symfony console commands.
  3. Database Schema:

    • Migrations are required after extending BaseScheduledCommand. Forgetting this will cause runtime errors.
  4. Permissions:

    • The /command-scheduler route is not secured by default. Always restrict access (e.g., ROLE_ADMIN) as shown in the setup.
  5. Time Zones:

    • Cron expressions are evaluated in the server’s time zone. Set TZ environment variables or configure Symfony’s timezone if needed:
      framework:
          timezone: Europe/Berlin
      

Debugging Tips

  1. Check Logs:

    • Failed executions log to var/log/dev.log (or prod.log). Look for SchedulerCommandFailedEvent.
  2. Enable Debug Mode:

    • Temporarily set APP_DEBUG=1 to see detailed errors in the UI or CLI.
  3. Validate Entities:

    • Use Symfony’s validator to check cron expressions before saving:
      $errors = $validator->validate($scheduledCommand);
      if (count($errors) > 0) {
          // Handle validation errors
      }
      
  4. Clear Cache:

    • After extending the ScheduledCommand entity, clear the cache:
      php bin/console cache:clear
      

Extension Points

  1. Custom Entity Fields:

    • Extend BaseScheduledCommand to add metadata (e.g., priority, teamId). Example:
      #[ORM\Column(type: 'integer')]
      private int $priority = 0;
      
  2. Override Templates:

    • Customize the Twig templates (located in vendor/dukecity/command-scheduler-bundle/Resources/views/) by copying them to templates/dukecity_command_scheduler/ and modifying.
  3. Event Listeners:

    • Subscribe to events like SchedulerCommandCreatedEvent to trigger side effects (e.g., send notifications):
      #[AsEventListener(SchedulerCommandCreatedEvent::class)]
      public function onCommandCreated(SchedulerCommandCreatedEvent $event): void
      {
          // Send email/Slack alert
      }
      
  4. Custom Command Loader:

    • Override the default command loader to filter or reorder commands:
      dukecity_command_scheduler:
          command_loader: App\Service\CustomCommandLoader
      

Pro Tips

  1. Bulk Scheduling: Use the ScheduledCommandFactory in a loop to create multiple schedules:

    foreach ($commands as $command) {
        $scheduledCommand = $this->factory->create();
        $scheduledCommand->setCommand($command['name']);
        $scheduledCommand->setCronExpression($command['cron']);
        // ...
    }
    
  2. Dynamic Cron Expressions: Fetch cron expressions from a config file or API:

    # config/packages/dukecity_command_scheduler.yaml
    dukecity_command_scheduler:
        cron_expressions:
            app:backup: "%env(BACKUP_CRON)%"
    
  3. Rate Limiting: Combine with Symfony’s RateLimiter to prevent overloading:

    use Symfony\Component\RateLimiter\RateLimiterFactory;
    
    $rateLimiter = RateLimiterFactory::create($container->getParameter('rate_limiter.token_bucket'));
    if (!$rateLimiter->consume($tokenBucket)->isAllowed()) {
        throw new \RuntimeException('Rate limit exceeded');
    }
    
  4. Docker/Serverless: For serverless environments (e.g., AWS Lambda), use the executeImmediately endpoint to trigger commands on-demand:

    curl -X POST /command-scheduler/detail/executeImmediately/{id}
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin