Installation
composer require bcc/resque-bundle
Add to config/bundles.php:
return [
// ...
BCC\ResqueBundle\BCCResqueBundle::class => ['all' => true],
];
Configuration
Edit config/packages/bcc_resque.yaml:
resque:
redis:
host: '127.0.0.1'
port: 6379
password: null
queues: ['default', 'high_priority']
First Job Create a job class:
namespace App\Jobs;
use BCC\ResqueBundle\Job\JobInterface;
class ProcessUser implements JobInterface
{
public function perform($data)
{
// Your logic here
}
}
Enqueue a Job
use BCC\ResqueBundle\Job\Job;
$job = new Job('App\Jobs\ProcessUser', ['data' => $userData]);
$job->enqueue();
Run Worker
php bin/console resque:worker default
// In your controller
$job = new Job('App\Jobs\SendWelcomeEmail', ['userId' => $user->id]);
$job->enqueue();
// In your job
public function perform($data)
{
Mail::to($data['userId'])->send(new WelcomeEmail());
}
Dependency Injection Use constructor injection for services:
class ProcessOrder implements JobInterface
{
private $orderService;
public function __construct(OrderService $orderService)
{
$this->orderService = $orderService;
}
public function perform($data)
{
$this->orderService->process($data['orderId']);
}
}
Job Chaining Enqueue follow-up jobs:
public function perform($data)
{
if ($data['needsFollowUp']) {
$followUpJob = new Job('App\Jobs\FollowUpTask', $data);
$followUpJob->enqueue();
}
}
Job Retry Logic
Implement shouldRetry() and retryDelay():
public function shouldRetry($failedAttempts, $data)
{
return $failedAttempts < 3;
}
public function retryDelay($failedAttempts, $data)
{
return 60 * $failedAttempts; // Exponential backoff
}
Dynamic Queue Assignment
$job = new Job('App\Jobs\HeavyTask', $data);
$job->setQueue($priority ? 'high_priority' : 'default');
$job->enqueue();
Bulk Processing
foreach ($users as $user) {
$job = new Job('App\Jobs\ProcessUser', ['userId' => $user->id]);
$job->enqueue();
}
Worker Management
php bin/console resque:worker default --count=4
php bin/console resque:stats
Symfony Events Listen to job events:
// config/services.yaml
BCC\ResqueBundle\EventListener\JobListener:
tags:
- { name: kernel.event_listener, event: resque.job.enqueued, method: onJobEnqueued }
Doctrine Integration Use transactions in jobs:
public function perform($data)
{
$entityManager = $this->getDoctrine()->getManager();
$entityManager->beginTransaction();
try {
// Process data
$entityManager->commit();
} catch (\Exception $e) {
$entityManager->rollBack();
throw $e;
}
}
API Job Triggering Create a controller endpoint:
#[Route('/jobs/process', name: 'app.job.process', methods: ['POST'])]
public function triggerJob(Request $request)
{
$job = new Job('App\Jobs\ProcessData', $request->request->all());
$job->enqueue();
return new JsonResponse(['status' => 'queued']);
}
Redis Connection Issues
config/packages/bcc_resque.yaml for correct credentials.resque:stats to verify connection.Job Serialization
json_encode()/json_decode() for complex data.Worker Crashes
public function perform($data)
{
try {
// Job logic
} catch (\Exception $e) {
// Log error
throw $e; // Re-throw to trigger retry
}
}
Queue Stuck Jobs
resque:remove to clean stuck jobs:
php bin/console resque:remove App\Jobs\StuckJob
Logging
Enable job logging in config/packages/bcc_resque.yaml:
resque:
logging: true
Check logs at var/log/resque.log.
Job Inspection
php bin/console resque:list
php bin/console resque:inspect App\Jobs\ProcessUser
Worker Debugging
php bin/console resque:worker default --debug
Redis Prefix Customize Redis keys with:
resque:
redis:
prefix: 'myapp_resque_'
Worker Timeout Adjust worker timeout (default: 25s):
resque:
worker_timeout: 60
Environment-Specific Config Use environment variables:
resque:
redis:
host: '%env(RESQUE_REDIS_HOST)%'
password: '%env(RESQUE_REDIS_PASSWORD)%'
Custom Job Classes
Extend BCC\ResqueBundle\Job\Job for custom behavior:
class CustomJob extends Job
{
public function __construct(string $class, array $args, array $options = [])
{
parent::__construct($class, $args, $options);
$this->setQueue('custom_queue');
}
}
Event Subscribers Create custom events:
class CustomJobEvent extends JobEvent
{
public function __construct(JobInterface $job, string $eventName)
{
parent::__construct($job, $eventName);
}
}
Middleware Add middleware to jobs:
$job = new Job('App\Jobs\ProcessData', $data);
$job->addMiddleware(new LoggingMiddleware());
$job->enqueue();
Batch Processing Process jobs in batches to reduce Redis overhead:
$batchSize = 20;
$batch = array_slice($items, 0, $batchSize);
foreach ($batch as $item) {
$job = new Job('App\Jobs\ProcessItem', ['item' => $item]);
$job->enqueue();
}
Queue Prioritization Use multiple queues for priority management:
resque:
queues:
- { name: 'critical', priority: 1 }
- { name: 'default', priority: 2 }
- { name: 'low', priority: 3 }
Worker Concurrency Adjust worker concurrency based on system resources:
php bin/console resque:worker default --concurrency=5
How can I help you explore Laravel packages today?