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

Cronjob Supervisor Laravel Package

toflar/cronjob-supervisor

Run and cap background workers using only a minutely cronjob—no supervisord needed. Define commands with desired concurrency; the supervisor tracks running processes and prevents overspawning across minutes via ps/tasklist/flock providers, working on Linux and Windows.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require toflar/cronjob-supervisor

Publish the config file (if needed):

php artisan vendor:publish --provider="Toflar\CronjobSupervisor\CronjobSupervisorServiceProvider"
  1. Basic Configuration Edit config/cronjob-supervisor.php to define your cron jobs:

    'jobs' => [
        'send-daily-reports' => [
            'command' => 'php artisan reports:send',
            'schedule' => '0 8 * * *',
            'description' => 'Send daily reports to users',
        ],
    ],
    
  2. First Use Case Register the supervisor in app/Console/Kernel.php:

    protected function schedule(Schedule $schedule)
    {
        $schedule->job(new \Toflar\CronjobSupervisor\CronjobSupervisorJob());
    }
    

    Run the supervisor manually for testing:

    php artisan schedule:run
    

Implementation Patterns

Workflow Integration

  1. Cron Job Management

    • Use the package to centralize cron job definitions in Laravel config instead of scattered crontab entries.
    • Example: Define a job with dependencies:
      'process-invoices' => [
          'command' => 'php artisan invoices:process',
          'schedule' => '*/15 * * * *',
          'before' => ['check-payments'],
          'after' => ['log-invoices'],
      ],
      
  2. Dynamic Scheduling

    • Leverage Laravel’s Schedule facade to dynamically adjust job timing:
      $schedule->job(new \Toflar\CronjobSupervisor\CronjobSupervisorJob())
          ->everyMinute()
          ->when(function () {
              return config('app.env') === 'production';
          });
      
  3. Logging and Monitoring

    • Integrate with Laravel’s logging system by extending the CronjobSupervisorJob:
      use Toflar\CronjobSupervisor\CronjobSupervisorJob;
      use Illuminate\Support\Facades\Log;
      
      class CustomCronjobSupervisorJob extends CronjobSupervisorJob
      {
          protected function logJobExecution($jobName, $result)
          {
              Log::info("Cronjob executed: {$jobName}. Result: " . ($result ? 'Success' : 'Failed'));
          }
      }
      
  4. Environment-Specific Jobs

    • Use conditional logic in config to enable/disable jobs per environment:
      'jobs' => [
          'cleanup-temp-files' => [
              'command' => 'php artisan temp:clean',
              'schedule' => '0 3 * * *',
              'environments' => ['staging', 'production'],
          ],
      ],
      

Gotchas and Tips

Common Pitfalls

  1. Cron Syntax Errors

    • Ensure cron syntax in schedule is correct (e.g., * * * * * for every minute). Test with crontab.guru.
    • Debug Tip: Use php artisan tinker to validate schedules:
      \Illuminate\Support\Facades\Schedule::call('send-daily-reports');
      
  2. Missing Dependencies

    • If jobs have before/after dependencies, ensure all referenced jobs exist in the config. Missing jobs will silently fail.
    • Fix: Add a validation step in a service provider:
      $this->validateCronJobs(config('cronjob-supervisor.jobs'));
      
  3. Time Zone Mismatches

    • Cron jobs run in the server’s time zone. Set Laravel’s time zone in .env:
      APP_TIMEZONE=America/New_York
      
    • Tip: Use now()->timezone('UTC')->format('Y-m-d H:i:s') for consistent logging.
  4. Artisan Command Failures

    • If a job’s command fails, the supervisor logs the exit code but doesn’t retry by default.
    • Workaround: Wrap the command in a try-catch block in a custom job class.

Performance and Precision

  1. High-Precision Scheduling
    • New in 2.1.3: The supervisor now uses high-precision bounded sleep in its supervision loop, reducing drift in job execution timing.
    • Impact: Jobs scheduled with tight intervals (e.g., every 30 seconds) will now execute closer to their intended time, minimizing overlap or missed runs.
    • Tip: For jobs requiring sub-second precision, consider using Laravel’s Schedule::call() with custom timing logic instead of cron syntax.

Extension Points

  1. Custom Job Handlers

    • Extend CronjobSupervisorJob to add pre/post hooks:
      class ExtendedSupervisorJob extends CronjobSupervisorJob
      {
          protected function beforeJob($jobName)
          {
              // Pre-execution logic (e.g., check DB connection)
          }
      
          protected function afterJob($jobName, $result)
          {
              // Post-execution logic (e.g., send Slack alert)
          }
      }
      
  2. Database-Backed Scheduling

    • Store job schedules in a database table (e.g., cron_jobs) and fetch them dynamically:
      $jobs = DB::table('cron_jobs')->where('active', 1)->get();
      foreach ($jobs as $job) {
          $schedule->command($job->command)->everyMinute();
      }
      
  3. Slack/Email Notifications

    • Integrate with Laravel Notifications to alert on failures:
      use Illuminate\Support\Facades\Notification;
      use App\Notifications\CronjobFailed;
      
      protected function afterJob($jobName, $result)
      {
          if (!$result) {
              Notification::route('mail', 'admin@example.com')
                          ->notify(new CronjobFailed($jobName));
          }
      }
      
  4. Docker/Serverless Considerations

    • For Docker, ensure the container’s cron service is enabled (cron: true in docker-compose.yml).
    • For serverless (e.g., AWS Lambda), replace cron with CloudWatch Events and invoke the Laravel app via API.

Debugging Tips

  • Log Output: Enable Laravel’s debug mode (APP_DEBUG=true) and check storage/logs/laravel.log.
  • Dry Runs: Use php artisan schedule:work to manually trigger jobs without waiting for cron.
  • Exit Codes: Check the exit code of failed jobs (e.g., 1 for command failure) in logs.
  • Precision Testing: For jobs with tight schedules, log the exact execution time:
    Log::debug("Job '{$jobName}' executed at: " . now()->toDateTimeString());
    

NO_UPDATE_NEEDED would not apply here due to the meaningful addition of precision improvements in the new release.
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.
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
spatie/mailcoach-vapor