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

Php Resque Scheduler Laravel Package

chrisboulton/php-resque-scheduler

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require chrisboulton/php-resque-scheduler
    

    Ensure php-resque is also installed (chrisboulton/php-resque).

  2. Configure Redis The scheduler relies on Redis for job persistence. Ensure your config/database.php has a Redis connection configured.

  3. Basic Setup Add the scheduler to your config/app.php service providers:

    'providers' => [
        // ...
        Chrisboulton\PhpResqueScheduler\SchedulerServiceProvider::class,
    ],
    
  4. First Use Case: Delayed Job Schedule a job to run in 5 minutes:

    use Chrisboulton\PhpResqueScheduler\Scheduler;
    
    $scheduler = app(Scheduler::class);
    $scheduler->schedule(
        'job_name', // Resque job name
        time() + 300, // Unix timestamp (5 minutes from now)
        ['param1' => 'value1'] // Job payload
    );
    

Implementation Patterns

Common Workflows

  1. Recurring Jobs Use scheduleRecurring() for periodic tasks (e.g., cron-like jobs):

    $scheduler->scheduleRecurring(
        'daily_backup',
        '0 3 * * *', // Cron syntax
        ['backup_path' => '/path/to/backup']
    );
    
  2. Dynamic Scheduling Schedule jobs based on runtime logic (e.g., user actions):

    $delay = $user->isPremium() ? 60 : 300; // 1 min for premium, 5 min for others
    $scheduler->schedule('send_email', time() + $delay, ['user_id' => $user->id]);
    
  3. Integration with Laravel Queues Use Resque::enqueue() for immediate jobs and Scheduler for delayed ones:

    if ($urgent) {
        Resque::enqueue('urgent_job', ['data' => $data]);
    } else {
        $scheduler->schedule('delayed_job', time() + 3600, ['data' => $data]);
    }
    
  4. Batch Processing Schedule multiple jobs at once:

    $jobs = [
        ['job' => 'process_order', 'args' => [$order->id], 'at' => time() + 10],
        ['job' => 'cleanup_logs', 'args' => [], 'at' => time() + 86400], // Tomorrow
    ];
    foreach ($jobs as $job) {
        $scheduler->schedule($job['job'], $job['at'], $job['args']);
    }
    

Integration Tips

  • Resque Workers: Run workers with the scheduler enabled:
    php resque.php -w worker_name --scheduler
    
  • Laravel Artisan: Schedule jobs from commands:
    use Chrisboulton\PhpResqueScheduler\Scheduler;
    
    class ScheduleCommand extends Command {
        protected $scheduler;
    
        public function __construct(Scheduler $scheduler) {
            $this->scheduler = $scheduler;
        }
    
        public function handle() {
            $this->scheduler->schedule('daily_report', time() + 86400);
        }
    }
    
  • Monitoring: Use Redis CLI to inspect scheduled jobs:
    redis-cli LRANGE resque:scheduler:jobs 0 -1
    

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues

    • Ensure Redis is running and accessible. Test with:
      redis-cli PING
      
    • If using Docker, verify port mappings and network configurations.
  2. Time Zone Mismatches

    • Cron syntax in scheduleRecurring() uses the server’s time zone. Convert timestamps explicitly if needed:
      $timestamp = Carbon::now()->timezone('UTC')->timestamp + 3600;
      
  3. Job Overlapping

    • Avoid scheduling the same job multiple times without deduplication. Use unique keys or check Redis for existing jobs:
      redis-cli EXISTS resque:job:unique_key
      
  4. Worker Stuck on Scheduler

    • If workers hang, restart them or check for locked jobs:
      redis-cli KEYS "resque:locked:*"
      

Debugging Tips

  • Log Scheduled Jobs: Extend the Scheduler class to log jobs:
    class CustomScheduler extends Scheduler {
        public function schedule($job, $at, $args = []) {
            Log::info("Scheduled job {$job} at {$at}");
            return parent::schedule($job, $at, $args);
        }
    }
    
  • Test Locally: Use a local Redis instance (e.g., redis-server) and mock the scheduler in tests:
    $this->app->instance(Scheduler::class, MockScheduler::class);
    

Extension Points

  1. Custom Job Classes Extend Chrisboulton\PhpResqueScheduler\Job to add metadata or validation:

    class CustomJob extends Job {
        public function validate($args) {
            if (empty($args['required_field'])) {
                throw new \InvalidArgumentException('Field is required');
            }
        }
    }
    
  2. Event Listeners Listen for job scheduling events (e.g., log or notify):

    event(new JobScheduled($job, $at, $args));
    
  3. Redis Key Prefixes Override the default Redis keys by binding a custom Redis instance:

    $this->app->bind('redis', function () {
        return Redis::connection('custom_redis');
    });
    
  4. Fallback for Failed Jobs Implement a retry mechanism for failed scheduled jobs:

    $scheduler->schedule('fallback_job', time() + 60, ['original_job' => $job]);
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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