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

Technical Evaluation

Architecture Fit

  • Sub-minute scheduling: Fills a critical gap in Laravel’s native scheduler (which is limited to 1-minute granularity). Ideal for use cases requiring high-frequency execution (e.g., real-time analytics, IoT data processing, or low-latency background tasks).
  • Non-blocking design: Leverages ReactPHP for event-driven execution, ensuring tasks run in parallel without blocking the main scheduler loop. This is a major advantage over Laravel’s default scheduler, which runs tasks sequentially in the foreground.
  • Process isolation: Each command runs in a separate process (via Symfony\Component\Process), preventing memory leaks or slow tasks from impacting the scheduler’s performance.
  • Constraints & conditions: Supports when(), between(), environments(), and onOneServer() constraints, enabling fine-grained control over task execution (e.g., time-based throttling, environment-specific runs).

Integration Feasibility

  • Laravel-native: Designed for Laravel (v9–13), with minimal friction for adoption. Integrates seamlessly with existing Console/Kernel.php and routes/console.php.
  • Facade & method injection: Provides both a facade (ShortSchedule) and a kernel method (shortSchedule()), offering flexibility in how schedules are defined.
  • Shell command support: Can execute arbitrary shell commands (e.g., ShortSchedule::exec('bash-script')->everySecond()), broadening use cases beyond Artisan commands.
  • Event-driven hooks: Emits ShortScheduledTaskStarting and ShortScheduledTaskStarted events, enabling observability and side effects (e.g., logging, metrics).

Technical Risk

  • ReactPHP dependency: Requires familiarity with non-blocking I/O and event loops. While the package abstracts this well, debugging ReactPHP-related issues (e.g., timer precision, process leaks) may require deeper PHP knowledge.
  • Process management: Relies on Supervisor (or similar) for process monitoring. Misconfiguration could lead to orphaned processes or downtime.
  • Sub-second precision: While theoretically possible (e.g., everySeconds(0.5)), system clock skew or OS scheduling latency may introduce variability in actual execution timing.
  • Memory leaks: Long-running workers must be managed via the --lifetime flag to avoid memory bloat (e.g., php artisan short-schedule:run --lifetime=60).
  • Blocking constraints: Custom when() closures or event listeners run in the loop, so slow logic will delay all scheduled tasks. Offload heavy work to queues.

Key Questions

  1. Use Case Validation:
    • Are sub-minute frequencies absolutely necessary, or could a queued job (e.g., everyMinute + delay) suffice?
    • Will tasks block the loop (e.g., slow when() conditions)? If so, how will this be mitigated (e.g., queue-based constraints)?
  2. Operational Overhead:
    • How will the ReactPHP worker be monitored? (Logs, metrics, alerts?)
    • What’s the failure recovery strategy for crashed workers? (Supervisor restarts? Health checks?)
  3. Scaling:
    • Will multiple instances of the scheduler run on the same server? If so, how will onOneServer() conflicts be handled?
    • How will process limits (e.g., max concurrent commands) be enforced?
  4. Testing:
    • How will sub-second timing be tested in CI/CD? (Mocking ReactPHP timers?)
    • Are there race conditions in constraints (e.g., when() + between())?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfect fit for Laravel apps needing high-frequency background tasks. Complements existing schedule:run without duplication.
  • PHP 8.3+: Requires modern PHP, but this aligns with Laravel 11/12/13’s baseline.
  • ReactPHP: Enables asynchronous execution, but the package abstracts this well. Teams unfamiliar with ReactPHP can use it without deep expertise.
  • Process Management Tools: Requires Supervisor (or PM2, systemd) for production deployment. This is a standard practice for long-running PHP workers.

Migration Path

  1. Pilot Phase:
    • Start with non-critical tasks (e.g., logging, analytics) to validate timing and reliability.
    • Use the facade syntax (ShortSchedule::command()) for simplicity.
  2. Kernel Integration:
    • Migrate schedules to shortSchedule() method in Console/Kernel.php for better organization.
  3. Constraint Rollout:
    • Gradually introduce constraints (when(), between()) based on need.
  4. Monitoring:
    • Instrument with events (e.g., log ShortScheduledTaskStarting) and metrics (e.g., execution latency).

Compatibility

  • Laravel Versions: Supports v9–13 (drop-in for v10/11/12; v13 requires PHP 8.3).
  • Artisan Commands: Works with any Artisan command, including custom ones.
  • Shell Commands: Supports arbitrary shell scripts (useful for non-PHP tasks).
  • Existing Schedules: Does not interfere with Laravel’s native scheduler (schedule:run). Runs as a separate process.

Sequencing

  1. Deploy Package:
    composer require spatie/laravel-short-schedule
    
  2. Define Schedules:
    • Add to routes/console.php or Console/Kernel.php:
      protected function shortSchedule(ShortSchedule $shortSchedule) {
          $shortSchedule->command('optimize:clear')->everySecond();
      }
      
  3. Configure Supervisor:
    • Add a config file (e.g., /etc/supervisor/conf.d/short-schedule.conf):
      [program:laravel-short-schedule]
      command=php /path/to/artisan short-schedule:run --lifetime=60
      autostart=true
      autorestart=true
      user=www-data
      numprocs=1
      
  4. Start Worker:
    supervisorctl reread
    supervisorctl update
    supervisorctl start laravel-short-schedule
    
  5. Validate:
    • Check logs for task execution:
      tail -f /path/to/storage/logs/laravel.log
      
    • Test constraints (e.g., when(), between()) in staging.

Operational Impact

Maintenance

  • Worker Lifecycle:
    • Use --lifetime to auto-restart workers and prevent memory leaks (e.g., --lifetime=3600 for hourly restarts).
    • Monitor process count (Supervisor/PM2) to detect leaks.
  • Configuration Drift:
    • Changes to schedules require worker restarts (Supervisor handles this automatically).
    • Use feature flags or database-backed schedules to avoid redeploys for minor changes.
  • Logging:
    • Log event emissions (ShortScheduledTaskStarting) for observability.
    • Capture process exit codes to detect task failures.

Support

  • Debugging:
    • Timer precision: Use everySeconds(1) and measure actual execution times (may vary due to OS scheduling).
    • Blocking constraints: Profile when() closures to ensure they execute <100ms.
    • Process isolation: Verify no shared state between tasks (each runs in a separate process).
  • Common Issues:
    • Worker crashes: Check Supervisor logs for segfaults or OOM kills.
    • Missed tasks: Ensure schedule:run (native) and short-schedule:run are both running.
    • Permission errors: Verify the worker user (e.g., www-data) has access to command paths.

Scaling

  • Horizontal Scaling:
    • Single server: Use onOneServer() to prevent duplicate runs across multiple workers.
    • Multi-server: Deploy one worker per server; use distributed locks (e.g., Redis) for critical tasks.
  • Load Testing:
    • Simulate high-frequency tasks (e.g., 1000 tasks/sec) to validate:
      • System resource usage (CPU, memory).
      • Database load (if tasks write to DB).
      • Process table limits (ulimit -u).
  • Auto-Scaling:
    • Use Kubernetes or ECS with horizontal pod autoscaling for dynamic workloads.
    • Monitor process count and scale workers based on queue depth.

Failure Modes

Failure Scenario Impact Mitigation
Worker process crashes Missed tasks Supervisor auto-restart + alerts
Memory leak in long-running task OOM kill --lifetime flag + monitoring
Slow when() constraint Delayed tasks Offload to queue + optimize constraint logic
Database connection exhaustion Task failures
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.
nexmo/api-specification
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
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata