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

Schedule Bundle Laravel Package

bkstg/schedule-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bkstg/schedule-bundle
    

    Register the bundle in config/app.php under providers:

    Backstage\ScheduleBundle\ScheduleServiceProvider::class,
    
  2. Publish Configuration

    php artisan vendor:publish --provider="Backstage\ScheduleBundle\ScheduleServiceProvider"
    

    This creates config/schedule.php with default settings.

  3. First Use Case: Basic Scheduling Define a scheduled job in app/Console/Kernel.php:

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('emails:send')->dailyAt('10:00');
    }
    

    Register the Kernel in app/Console/Kernel.php:

    protected $commands = [
        \Backstage\ScheduleBundle\Console\ScheduleCommand::class,
    ];
    
  4. Run the Scheduler

    php artisan schedule:run
    

    For production, set up a cron job (e.g., * * * * * cd /path-to-project && php artisan schedule:run >> /dev/null 2>&1).


Implementation Patterns

Core Workflows

  1. Command-Based Scheduling

    • Schedule Laravel commands directly:
      $schedule->command('backup:run')->hourly();
      
    • Pass arguments dynamically:
      $schedule->command('report:generate {argument}')->daily()->withArguments(['--type=monthly']);
      
  2. Closure-Based Jobs

    • Define ad-hoc tasks:
      $schedule->call(function () {
          Log::info('Running custom scheduled task');
          // Business logic here
      })->everyFiveMinutes();
      
  3. Event-Based Triggers

    • Schedule jobs tied to events (e.g., after deployment):
      $schedule->job(new DeployPostHookJob)->after('deploy');
      
  4. Environment-Specific Scheduling

    • Use when() to conditionally run jobs:
      $schedule->command('cache:clear')->when(function () {
          return app()->environment('production');
      })->weekly();
      

Integration Tips

  1. Database Backend

    • Enable the database scheduler by setting SCHEDULE_RUNNER=database in .env and running:
      php artisan schedule:install
      
    • Jobs are stored in scheduled_tasks table; verify with:
      \Backstage\ScheduleBundle\Models\ScheduledTask::latest()->take(10)->get();
      
  2. Custom Job Classes

    • Extend \Backstage\ScheduleBundle\Jobs\Job for reusable logic:
      namespace App\Jobs\Scheduled;
      
      use Backstage\ScheduleBundle\Jobs\Job;
      
      class CleanupJob extends Job
      {
          public function handle()
          {
              // Custom logic
          }
      }
      
    • Schedule via:
      $schedule->job(new \App\Jobs\Scheduled\CleanupJob)->daily();
      
  3. Logging and Monitoring

    • Log job execution in app/Console/Kernel.php:
      $schedule->command('log:clean')->daily()->onOneServer();
      
    • Monitor via Laravel Horizon (if installed) or custom logging:
      $schedule->call(function () {
          \Log::debug('Scheduled task executed at: ' . now());
      })->everyMinute();
      
  4. Testing

    • Mock the scheduler in tests:
      $schedule = $this->app->make(\Backstage\ScheduleBundle\Schedule::class);
      $schedule->shouldReceive('command')->once()->with('test:run');
      

Gotchas and Tips

Pitfalls

  1. Cron Misconfiguration

    • Ensure the cron job runs every minute (* * * * *). Without this, the scheduler won’t execute.
    • Fix: Verify cron with:
      crontab -l
      
  2. Timezone Issues

    • The scheduler uses the system timezone by default. Override in config/schedule.php:
      'timezone' => 'America/New_York',
      
    • Debug: Check timezone with:
      \Carbon\Carbon::now()->timezone;
      
  3. Database Locking

    • If using the database runner, ensure scheduled_tasks table has proper indexes:
      Schema::table('scheduled_tasks', function (Blueprint $table) {
          $table->index('due_at');
          $table->index('status');
      });
      
    • Symptom: Slow job execution or timeouts.
  4. Overlapping Jobs

    • Jobs scheduled too frequently (e.g., every 30 seconds) may cause race conditions.
    • Mitigation: Use onOneServer() or withoutOverlapping():
      $schedule->command('long-running:task')->everyThirtyMinutes()->onOneServer();
      

Debugging

  1. Check Last Run

    • Inspect the scheduled_tasks table or log files for the last execution time:
      SELECT * FROM scheduled_tasks ORDER BY id DESC LIMIT 1;
      
  2. Force Run

    • Manually trigger a job for testing:
      php artisan schedule:run --force
      
  3. Disable Jobs

    • Temporarily disable all jobs by setting SCHEDULE_ENABLED=false in .env.
  4. Log Output

    • Redirect scheduler logs to a file:
      php artisan schedule:run >> /var/log/schedule.log 2>&1
      

Extension Points

  1. Custom Runners

    • Extend \Backstage\ScheduleBundle\Runners\RunnerInterface for alternative runners (e.g., Redis):
      namespace App\Runners;
      
      use Backstage\ScheduleBundle\Runners\RunnerInterface;
      
      class RedisRunner implements RunnerInterface
      {
          public function run()
          {
              // Custom Redis-based logic
          }
      }
      
    • Bind the runner in ScheduleServiceProvider:
      $this->app->bind(RunnerInterface::class, function () {
          return new \App\Runners\RedisRunner();
      });
      
  2. Job Events

    • Listen for job events (e.g., JobStarting, JobFinished) via Laravel events:
      event(new \Backstage\ScheduleBundle\Events\JobStarting(
          $job,
          $schedule
      ));
      
  3. Dynamic Scheduling

    • Fetch schedules from a database or API:
      $schedules = \App\Models\DynamicSchedule::where('active', true)->get();
      foreach ($schedules as $schedule) {
          $this->schedule->command($schedule->command)
              ->{$schedule->frequency}()
              ->at($schedule->time);
      }
      
  4. Rate Limiting

    • Implement custom rate limiting for jobs:
      $schedule->command('api:rate-limit-check')->everyFiveMinutes()
          ->limit(1)->withoutOverlapping();
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky