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

Job Queue Bundle Laravel Package

ddereszewski/job-queue-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require ddereszewski/job-queue-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Ddereszewski\JobQueueBundle\DdereszewskiJobQueueBundle::class => ['all' => true],
    ];
    
  2. Enable the Worker Run the worker process in a terminal (preferably in a screen/tmux session or as a systemd service):

    php bin/console jms:job:worker
    

    Note: Requires a running Symfony application (e.g., php bin/console server:run in another terminal).

  3. First Job Tag a console command to be queueable:

    // src/Command/MyCommand.php
    namespace App\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    use JMS\JobQueueBundle\Annotation as JMS;
    
    class MyCommand extends Command {
        protected static $defaultName = 'app:my-command';
    
        #[JMS\Job]
        public function execute(InputInterface $input, OutputInterface $output) {
            $output->writeln('Running in background!');
            return Command::SUCCESS;
        }
    }
    
  4. Dispatch a Job Enqueue the command via the jms:job:dispatch command:

    php bin/console jms:job:dispatch app:my-command
    

Where to Look First

  • Official Docs – Covers annotations, workers, and advanced configurations.
  • config/packages/jms_job_queue.yaml – Default configuration (adjust queues, retries, etc.).
  • src/Command/ – Scan for existing commands tagged with @JMS\Job to understand usage patterns.

Implementation Patterns

Core Workflows

1. Tagging Commands for Background Processing

Use the @JMS\Job annotation on any console command method to enable queuing:

#[JMS\Job(
    queue: 'high_priority', // Optional: Custom queue name
    delay: 3600,           // Optional: Delay in seconds
    priority: 10           // Optional: Priority (higher = sooner)
)]
public function execute(InputInterface $input, OutputInterface $output) {
    // ...
}

2. Dispatching Jobs Programmatically

Inject the JobDispatcherInterface service to enqueue jobs from controllers/services:

use JMS\JobQueueBundle\Job\JobDispatcherInterface;

class MyService {
    public function __construct(private JobDispatcherInterface $dispatcher) {}

    public function triggerJob() {
        $this->dispatcher->dispatch('app:my-command', [], 'high_priority');
    }
}

3. Handling Job Results

Use @JMS\JobResult to capture output/return values:

#[JMS\JobResult]
public function execute(InputInterface $input, OutputInterface $output) {
    return ['status' => 'success', 'data' => $this->processData()];
}

Retrieve results via:

php bin/console jms:job:result <job-id>

4. Dynamic Job Parameters

Pass arguments when dispatching:

php bin/console jms:job:dispatch app:my-command -- --param="value"

Access in the command:

$param = $input->getArgument('param');

Integration Tips

With Laravel (Symfony)

  • Service Providers: Register the bundle in config/app.php under extra.bundles.
  • Artisan Commands: Prefix commands with app: (e.g., app:my-command) to avoid conflicts.
  • Environment Variables: Configure queues in .env:
    JMS_JOB_QUEUE_CONNECTION=doctrine
    JMS_JOB_QUEUE_DSN=mysql://user:pass@localhost/db
    

Scaling Workers

  • Run multiple workers for parallel processing:
    php bin/console jms:job:worker --queue=high_priority &
    php bin/console jms:job:worker --queue=low_priority &
    
  • Use --limit=N to process N jobs per run (useful for long-running tasks).

Monitoring

  • Check job status:
    php bin/console jms:job:list
    php bin/console jms:job:show <job-id>
    
  • Log worker activity to var/log/jms_job_queue.log.

Gotchas and Tips

Pitfalls

  1. Worker Must Be Running

    • Jobs won’t execute if the worker process isn’t active. Test with:
      php bin/console jms:job:worker --verbose
      
    • Fix: Use a process manager (e.g., Supervisor) for production.
  2. Annotation Parsing Issues

    • Ensure jms/serializer-bundle is installed (required for annotation parsing).
    • Fix: Run composer require jms/serializer-bundle if missing.
  3. Queue Locking

    • Jobs may hang if the worker crashes mid-execution. Use --timeout=300 to limit runtime.
  4. Symfony 6+ Compatibility

    • The bundle is tested up to Symfony 5.4. For Symfony 6+, ensure symfony/console and symfony/dependency-injection are compatible.
  5. Doctrine DBAL Dependency

    • The default storage uses Doctrine DBAL. For other databases (e.g., PostgreSQL), configure JMS_JOB_QUEUE_DSN:
      JMS_JOB_QUEUE_DSN=pgsql://user:pass@localhost/db
      

Debugging

  • Worker Logs: Check var/log/jms_job_queue.log for errors.
  • Job Stuck? Restart the worker or manually delete the job from the database:
    DELETE FROM jms_job_queue_job WHERE id = <job-id>;
    
  • Command Not Found: Verify the command is registered in config/console or use the full namespace (e.g., App\Command\MyCommand).

Tips

  1. Custom Queues Define multiple queues in config/packages/jms_job_queue.yaml:

    jms_job_queue:
        queues:
            high_priority:
                max_jobs: 10
                timeout: 60
            low_priority:
                max_jobs: 50
                timeout: 300
    
  2. Retry Logic Use @JMS\JobRetry to auto-retry failed jobs:

    #[JMS\JobRetry(maxAttempts: 3, delay: 10)]
    public function execute(InputInterface $input, OutputInterface $output) {
        // ...
    }
    
  3. Event Listeners Hook into job lifecycle events (e.g., jms_job_queue.job.enqueue):

    // src/EventListener/JobListener.php
    use JMS\JobQueueBundle\Event\JobEvent;
    
    class JobListener {
        public function onJobEnqueue(JobEvent $event) {
            // Log or notify when a job is queued
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\JobListener:
            tags:
                - { name: kernel.event_listener, event: jms_job_queue.job.enqueue, method: onJobEnqueue }
    
  4. Testing Use JobDispatcherInterface in tests to mock job dispatching:

    $dispatcher = $this->createMock(JobDispatcherInterface::class);
    $dispatcher->expects($this->once())->method('dispatch');
    $this->container->set(JobDispatcherInterface::class, $dispatcher);
    
  5. Performance

    • Batch jobs with --batch-size=N to reduce database overhead.
    • For CPU-heavy tasks, offload to a separate server and use a remote queue (e.g., RabbitMQ via jms_job_queue.transport).
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware