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

Scheduled Command Bundle Laravel Package

carles/scheduled-command-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require carles/scheduled-command-bundle
    

    Ensure your server has the Unix at command installed (sudo apt-get install at on Debian/Ubuntu).

  2. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        Carles\ScheduledCommandBundle\CarlesScheduledCommandBundle::class => ['all' => true],
    ];
    
  3. Configure the Bundle Update config/packages/scheduled_command.yaml (or create it):

    scheduled_command:
        temp_command_files_dir: '%kernel.project_dir%/var/scheduled_commands'
    
  4. First Use Case Schedule a simple command via a controller or CLI:

    use Carles\ScheduledCommandBundle\Entity\ScheduledCommand;
    
    $scheduledCommand = new ScheduledCommand();
    $scheduledCommand->setCommand('php /path/to/your/console-command');
    $scheduledCommand->setDatetime(new \DateTime('+1 day')); // Run once in 24 hours
    
    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->persist($scheduledCommand);
    $entityManager->flush();
    

Implementation Patterns

Workflows

  1. One-Time Commands Use setDatetime() to schedule a command for a specific future time:

    $scheduledCommand->setDatetime(new \DateTime('2024-12-31 23:59:59'));
    
  2. Recurring Commands Combine with a cron-like approach by creating multiple ScheduledCommand entities (no built-in recurrence, but you can automate this with a separate job).

  3. Dynamic Command Generation Generate commands dynamically (e.g., passing arguments):

    $scheduledCommand->setCommand(
        'php artisan your:command --user={$userId} --force'
    );
    
  4. Integration with Symfony Console Schedule Symfony console commands directly:

    $scheduledCommand->setCommand('php bin/console app:send-emails');
    

Integration Tips

  • Doctrine Events: The bundle listens to prePersist and preUpdate events to trigger the at command. Ensure your ScheduledCommand entity is properly mapped.
  • Error Handling: Wrap persistence in a try-catch block to handle at command failures gracefully.
  • Logging: Log the scheduled command ID and datetime for debugging:
    $this->logger->info('Scheduled command', [
        'command' => $scheduledCommand->getCommand(),
        'datetime' => $scheduledCommand->getDatetime()->format('Y-m-d H:i:s'),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Unix Dependency

    • The bundle only works on Unix-like systems (Linux/macOS). Windows users must use alternatives like schtasks or third-party libraries.
    • Verify at is installed with which at in your terminal.
  2. File Permissions

    • The temp_command_files_dir must be writable by the web server user (e.g., www-data or nginx).
    • Default /tmp may not be ideal; specify a custom directory in config:
      scheduled_command:
          temp_command_files_dir: '%kernel.project_dir%/var/scheduled_commands'
      
  3. Command Length Limits

    • The at command has a 1024-character limit for arguments. Split long commands or use environment variables:
      $scheduledCommand->setCommand('php script.php --env=' . getenv('APP_ENV'));
      
  4. Timezone Issues

    • Ensure setDatetime() uses a timezone-aware DateTime object:
      $dateTime = new \DateTime('+1 hour', new \DateTimeZone('UTC'));
      $scheduledCommand->setDatetime($dateTime);
      
  5. Debugging Scheduled Jobs

    • Check if the at job was created by listing pending jobs:
      at -l
      
    • Verify the command file exists in temp_command_files_dir.

Tips

  1. Cleanup Old Commands Add a cron job to remove old command files (e.g., older than 30 days):

    find /path/to/scheduled_commands -type f -mtime +30 -delete
    
  2. Extend the Entity Add custom fields to ScheduledCommand (e.g., userId, status) and update the bundle’s Doctrine mapping:

    // src/Entity/ScheduledCommand.php
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $userId;
    
  3. Override the Command Writer Extend the bundle’s CommandWriter service to customize how commands are written to files:

    # config/services.yaml
    Carles\ScheduledCommandBundle\CommandWriter:
        arguments:
            $tempDir: '%kernel.project_dir%/var/custom_commands'
            $filePrefix: 'custom_'
    
  4. Testing Mock the at command in tests using a library like php-at or override the bundle’s AtCommandExecutor service:

    $this->container->set('carles_scheduled_command.at_command_executor', $mockExecutor);
    
  5. Security

    • Sanitize command inputs to prevent injection:
      $safeCommand = escapeshellarg($userInput);
      $scheduledCommand->setCommand($safeCommand);
      
    • Restrict who can schedule commands (e.g., via Symfony’s voter system).
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui