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

Console Command Scheduler Bundle Laravel Package

bytespin/console-command-scheduler-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bytespin/console-command-scheduler-bundle
    

    Register the bundle in config/bundles.php (automatically handled by Composer).

  2. Configure Scheduler: Add a YAML config file at config/packages/console_command_scheduler.yaml:

    console_command_scheduler:
        commands:
            app:send_emails:
                schedule: '0 12 * * *'  # Cron syntax
                timezone: 'Europe/Paris'
                max_runtime: 3600       # Max execution time in seconds
    
  3. First Use Case: Schedule a command (e.g., app:send_emails) by defining it in the config above. Run the scheduler worker:

    php bin/console console-command-scheduler:run
    
  4. Verify: Check the database (console_command_scheduler_command table) and logs (var/log/console_command_scheduler.log) for execution records.


Implementation Patterns

Core Workflow

  1. Define Commands: Configure commands in console_command_scheduler.yaml with cron syntax, timezones, and runtime limits.

    console_command_scheduler:
        commands:
            app:backup_database:
                schedule: '0 3 * * 0'  # Weekly on Sunday at 3 AM
                timezone: 'UTC'
                max_runtime: 7200
    
  2. Run the Scheduler: Use the CLI command to execute scheduled tasks:

    php bin/console console-command-scheduler:run
    

    For production, set up a cron job (e.g., * * * * * php /path/to/bin/console console-command-scheduler:run).

  3. Integrate with EasyAdmin (Optional): If using EasyAdmin, register the Command entity in your admin dashboard:

    // src/Admin/CommandAdmin.php
    use Bytespin\ConsoleCommandSchedulerBundle\Entity\Command;
    
    class CommandAdmin extends AbstractCrudController
    {
        public static function getEntityFqcn(): string { return Command::class; }
    }
    
  4. Event-Driven Extensions: Listen to events for custom logic (e.g., notifications):

    // src/EventListener/CommandEventListener.php
    use Bytespin\ConsoleCommandSchedulerBundle\Event\CommandEvent;
    
    class CommandEventListener
    {
        public function onCommandExecuted(CommandEvent $event): void
        {
            if ($event->getCommand()->getReturnCode() !== 0) {
                // Send alert
            }
        }
    }
    

    Register the listener in services.yaml:

    services:
        App\EventListener\CommandEventListener:
            tags:
                - { name: 'kernel.event_listener', event: 'console_command_scheduler.command.executed' }
    
  5. Notifications: Extend the notification system by implementing Bytespin\ConsoleCommandSchedulerBundle\Notification\NotificationInterface:

    class SlackNotification implements NotificationInterface
    {
        public function notify(Command $command): void
        {
            // Send Slack message
        }
    }
    

    Register it in services.yaml:

    services:
        App\Notification\SlackNotification:
            tags: ['console_command_scheduler.notification']
    

Gotchas and Tips

Pitfalls

  1. Database Schema Updates:

    • After updating the bundle (especially 1.0.13+), always run:
      php bin/console doctrine:schema:update --force
      
    • Ignoring this may cause runtime errors or missing logs.
  2. Timezone Mismatches:

    • Ensure the timezone in your config matches the server’s timezone to avoid scheduling conflicts.
    • Test with TZ=Europe/Paris php bin/console console-command-scheduler:run if unsure.
  3. Max Runtime Enforcement:

    • The max_runtime setting forcefully terminates commands exceeding the limit. Avoid long-running commands without proper error handling.
  4. EasyAdmin Dependency:

    • The admin interface requires EasyCorp/EasyAdminBundle. If not installed, the Command entity won’t be accessible via the dashboard.
    • Install it separately:
      composer require easycorp/easy-admin-bundle
      
  5. Cron Syntax Errors:

    • Validate cron syntax using tools like crontab.guru to avoid silent failures.
    • Example of a common mistake:
      schedule: '0 12 * * *'  # Correct (runs daily at 12 PM)
      schedule: '0 12 * *'   # Incorrect (missing day-of-week)
      
  6. Logging Overrides:

    • The bundle logs to var/log/console_command_scheduler.log. To customize the logger:
      # config/packages/monolog.yaml
      services:
          Bytespin\ConsoleCommandSchedulerBundle\Logger\CommandLogger:
              arguments:
                  $logger: '@monolog.logger.console_command_scheduler'
      

Debugging Tips

  1. Check Execution Logs:

    • Inspect var/log/console_command_scheduler.log for errors or execution details.
    • Enable debug mode (APP_DEBUG=1) for verbose output.
  2. Dry Run:

    • Test scheduling without executing commands by setting max_runtime: 0 (commands will start but terminate immediately).
  3. Event Debugging:

    • Use Symfony’s event dispatcher debug tool:
      php bin/console debug:event-dispatcher
      
    • Filter for console_command_scheduler events to verify listeners are attached.
  4. Database Inspection:

    • Query the console_command_scheduler_command table to verify records:
      SELECT * FROM console_command_scheduler_command ORDER BY executed_at DESC;
      

Extension Points

  1. Custom Command Metadata:

    • Extend the Command entity to store additional metadata (e.g., priority, environment_vars):
      // src/Entity/ExtendedCommand.php
      #[ORM\Entity]
      class ExtendedCommand extends Command
      {
          #[ORM\Column]
          private ?int $priority = 0;
      
          // Add getters/setters
      }
      
    • Update the bundle’s Command entity mapping in config/packages/doctrine.yaml if needed.
  2. Dynamic Scheduling:

    • Override the scheduler’s CommandScheduler service to fetch schedules dynamically (e.g., from an API):
      services:
          Bytespin\ConsoleCommandSchedulerBundle\Scheduler\CommandScheduler:
              arguments:
                  $commandRepository: '@app.custom_command_repository'
      
  3. Parallel Execution:

    • Use Symfony’s Messenger component to run commands in parallel (requires additional setup):
      framework:
          messenger:
              transports:
                  async: '%env(MESSENGER_TRANSPORT_DSN)%'
      
    • Configure the bundle to use the async transport for scheduled commands.
  4. Retries for Failed Commands:

    • Implement a retry mechanism by extending the CommandExecutor:
      class RetryCommandExecutor implements CommandExecutorInterface
      {
          public function execute(Command $command): int
          {
              $retries = 3;
              while ($retries--) {
                  $returnCode = $this->originalExecutor->execute($command);
                  if ($returnCode === 0) return $returnCode;
                  sleep(10); // Delay between retries
              }
              return $returnCode;
          }
      }
      
    • Replace the default executor in services.yaml:
      services:
          Bytespin\ConsoleCommandSchedulerBundle\Executor\CommandExecutor:
              class: App\Executor\RetryCommandExecutor
      
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