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

Laravel Short Schedule Laravel Package

spatie/laravel-short-schedule

Run Laravel Artisan commands at sub-minute intervals (every second or even 0.5s). Adds a short-scheduler powered by a ReactPHP event loop, running separately from schedule:run so high-frequency tasks don’t block or get delayed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-short-schedule
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Spatie\ShortSchedule\ShortScheduleServiceProvider"
    
  2. Define Short Schedule: In app/Console/Kernel.php, add the shortSchedule method:

    protected function shortSchedule(ShortSchedule $shortSchedule)
    {
        $shortSchedule->command('your:command')->everySecond();
    }
    
  3. Run the Scheduler: Start the short scheduler in production:

    php artisan short-schedule:run
    

    Use a process manager (e.g., Supervisor) to keep it running.


First Use Case: Real-Time Data Sync

Schedule a command to sync data every 5 seconds (e.g., for live updates):

ShortSchedule::command('sync:data')->everySeconds(5);

Implementation Patterns

Core Workflows

  1. Sub-Minute Scheduling:

    • Replace Laravel’s native scheduler for high-frequency tasks (e.g., polling APIs, real-time analytics).
    • Example: Run a command every 0.5 seconds (sub-second precision):
      ShortSchedule::command('process:events')->everySeconds(0.5);
      
  2. Constraints Integration:

    • Combine with Laravel’s native constraints (e.g., when, between):
      ShortSchedule::command('clean:cache')
          ->when(fn() => Cache::size() > 1000)
          ->everySeconds(30);
      
  3. Environment-Specific Tasks:

    • Restrict tasks to environments (e.g., staging/production):
      ShortSchedule::command('monitor:health')
          ->environments(['production', 'staging'])
          ->everySecond();
      

Integration Tips

  1. Process Isolation:

    • Each command runs in a separate process (via Symfony\Component\Process). Avoid blocking the event loop with heavy logic—offload to queues.
  2. Memory Management:

    • Set a --lifetime flag to auto-restart the worker (e.g., every 60 seconds):
      php artisan short-schedule:run --lifetime=60
      
  3. Event Listeners:

    • Use events (e.g., ShortScheduledTaskStarting) for pre/post-execution logic:
      ShortScheduledTaskStarting::dispatch(function ($event) {
          Log::info("Starting: {$event->command}");
      });
      
  4. Composite Constraints:

    • Chain constraints for granular control:
      ShortSchedule::command('backup:db')
          ->between('02:00', '04:00')
          ->environments('production')
          ->everyHours(1);
      

Gotchas and Tips

Pitfalls

  1. Blocking the Event Loop:

    • Avoid slow logic in when() closures or event listeners. Example:
      // ❌ Bad: Heavy DB query in closure
      ShortSchedule::command('sync')->when(fn() => DB::table('large_table')->count())->everySecond();
      
    • Fix: Use queues or pre-compute values.
  2. Overlapping Tasks:

    • By default, tasks run concurrently. Use withoutOverlapping() to enforce sequential execution:
      ShortSchedule::command('critical:task')->everySecond()->withoutOverlapping();
      
  3. Maintenance Mode:

    • Tasks skip execution during maintenance unless explicitly allowed:
      ShortSchedule::command('emergency:fix')->everySecond()->runInMaintenanceMode();
      
  4. Process Manager Quirks:

    • Supervisor may not forward signals correctly. Use --lifetime to force restarts:
      php artisan short-schedule:run --lifetime=3600
      

Debugging Tips

  1. Log Output:

    • Redirect logs to a file for debugging:
      php artisan short-schedule:run --log-file=/var/log/short-schedule.log
      
  2. Check Process Status:

    • Verify the worker is running:
      ps aux | grep short-schedule
      
  3. Test Locally:

    • Use php artisan short-schedule:run directly (without Supervisor) for development.

Extension Points

  1. Custom Commands:

    • Schedule class-based commands (automatically resolves signature):
      ShortSchedule::command(\App\Console\ProcessWebhooks::class)->everySeconds(10);
      
  2. Shell Commands:

    • Execute bash scripts:
      ShortSchedule::exec('php artisan optimize:clear')->everyDay();
      
  3. Dynamic Scheduling:

    • Adjust intervals at runtime (e.g., scale based on load):
      $interval = config('app.high_load') ? 0.1 : 1;
      ShortSchedule::command('scale:resources')->everySeconds($interval);
      

Pro Tips

  • Monitor Performance: Use top or htop to check CPU/memory usage of the worker.
  • Graceful Shutdown: Handle SIGTERM in Supervisor to avoid abrupt kills.
  • Testing: Mock the event loop in tests using Spatie\ShortSchedule\Testing\ShortScheduleFakes.
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai