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

Tasking Bundle Laravel Package

badpixxel/tasking-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require badpixxel/tasking-bundle
    

    Add the bundle to config/bundles.php in Symfony:

    return [
        // ...
        BadPixxel\TaskingBundle\BadPixxelTaskingBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Publish the default config:

    php bin/console badpixxel:tasking:install
    

    Review config/packages/badpixxel_tasking.yaml for queue/transport settings (e.g., doctrine, redis, or amqp).

  3. First Task Define a task class (e.g., src/Task/MyTask.php):

    namespace App\Task;
    
    use BadPixxel\TaskingBundle\Task\TaskInterface;
    
    class MyTask implements TaskInterface
    {
        public function execute(): void
        {
            // Your logic here
        }
    }
    
  4. Dispatch a Task

    use BadPixxel\TaskingBundle\Task\TaskDispatcherInterface;
    
    class MyController
    {
        public function __construct(private TaskDispatcherInterface $dispatcher) {}
    
        public function runTask()
        {
            $this->dispatcher->dispatch(new MyTask());
        }
    }
    
  5. Run the Worker

    php bin/console badpixxel:tasking:worker
    

Where to Look First

  • Documentation: Check the GitLab Wiki for advanced features (e.g., retries, timeouts, dependencies).
  • Default Config: config/packages/badpixxel_tasking.yaml for queue/transport settings.
  • Task Interface: src/Task/TaskInterface.php to understand required methods (execute(), getName()).
  • Commands: List available commands with:
    php bin/console list badpixxel:tasking
    

First Use Case: Background Processing

Dispatch a task to process a large CSV file without blocking the HTTP request:

$this->dispatcher->dispatch(new ProcessCsvTask($filePath));

The worker handles execution asynchronously.


Implementation Patterns

Core Workflows

  1. Task Dispatching

    • Basic: Dispatch tasks via TaskDispatcherInterface (e.g., in controllers/services).
    • Bulk Dispatch: Use dispatchMultiple() for batch processing:
      $this->dispatcher->dispatchMultiple([
          new TaskA(),
          new TaskB(),
      ]);
      
    • Delayed Tasks: Schedule tasks for later execution:
      $this->dispatcher->dispatch(new MyTask(), new \DateTime('+1 hour'));
      
  2. Task Dependencies Link tasks sequentially or in parallel:

    # config/packages/badpixxel_tasking.yaml
    badpixxel_tasking:
        tasks:
            task_a:
                depends_on: [task_b, task_c]
    
  3. Result Handling

    • Synchronous: Fetch results via TaskResultRepository:
      $result = $this->resultRepository->getResult($taskId);
      
    • Asynchronous: Use callbacks or webhooks (if configured).
  4. Worker Management

    • Multiple Workers: Run workers in separate processes/terminals for parallelism.
    • Worker Types: Configure different workers for different task types (e.g., high_priority_worker).

Integration Tips

  1. Symfony Events Trigger tasks from Symfony events (e.g., kernel.terminate):

    use Symfony\Component\HttpKernel\Event\TerminateEvent;
    
    $event->getRequest()->getSession()->getFlashbag()->add(...);
    $this->dispatcher->dispatch(new CleanupSessionTask());
    
  2. Doctrine Integration Use Doctrine tasks for database-heavy operations:

    badpixxel_tasking:
        transports:
            doctrine:
                enabled: true
                connection: default
    
  3. Retry Mechanisms Configure retries in config/packages/badpixxel_tasking.yaml:

    badpixxel_tasking:
        retries:
            max_attempts: 3
            delay: 60
    
  4. Monitoring

    • Log task execution with TaskLoggerInterface.
    • Extend with Prometheus metrics or custom logging.

Advanced Patterns

  1. Task Chaining Chain tasks dynamically in a service:

    $taskA = new TaskA();
    $taskB = new TaskB();
    $taskA->setNext($taskB); // Custom chaining logic
    $this->dispatcher->dispatch($taskA);
    
  2. Task Prioritization Use custom priority queues (e.g., high, medium, low) via transport configuration.

  3. Task Serialization Implement TaskInterface::serialize() and unserialize() for complex payloads.

  4. Testing Mock TaskDispatcherInterface in unit tests:

    $dispatcher = $this->createMock(TaskDispatcherInterface::class);
    $dispatcher->expects($this->once())->method('dispatch');
    

Gotchas and Tips

Pitfalls

  1. Worker Stuck in Loop

    • Cause: Unhandled exceptions in TaskInterface::execute() crash the worker.
    • Fix: Wrap logic in try-catch and log errors:
      public function execute(): void
      {
          try {
              // Task logic
          } catch (\Throwable $e) {
              $this->logger->error($e->getMessage(), ['task' => $this->getName()]);
              throw $e; // Re-throw to trigger retry
          }
      }
      
  2. Task Timeout

    • Cause: Long-running tasks exceed task_timeout (default: 60 seconds).
    • Fix: Increase timeout in config or split tasks into smaller chunks.
  3. Queue Blocking

    • Cause: Workers consume tasks faster than they’re dispatched, leading to idle workers.
    • Fix: Adjust worker concurrency or use dispatchMultiple() for bursts.
  4. Serialization Issues

    • Cause: Complex objects (e.g., closures, resources) fail to serialize.
    • Fix: Implement TaskInterface::serialize()/unserialize() or avoid non-serializable data.

Debugging Tips

  1. Worker Logs Enable verbose logging in config/packages/badpixxel_tasking.yaml:

    badpixxel_tasking:
        logging:
            level: debug
    

    Check logs at var/log/dev.log.

  2. Task Inspection List pending tasks:

    php bin/console badpixxel:tasking:list
    

    View task details:

    php bin/console badpixxel:tasking:show <task_id>
    
  3. Transport-Specific Issues

    • Doctrine: Ensure the connection is healthy (php bin/console doctrine:database:status).
    • Redis: Verify Redis server is running and accessible.
    • AMQP: Check RabbitMQ queues with rabbitmqctl list_queues.

Configuration Quirks

  1. Default Transport The bundle defaults to doctrine if no transport is configured. Explicitly set your preferred transport:

    badpixxel_tasking:
        transport: redis
    
  2. Task Naming Tasks without a getName() method use their class name. Override for clarity:

    public function getName(): string
    {
        return 'custom.task.name';
    }
    
  3. Worker Auto-Start Workers do not start automatically. Always run them manually or via a process manager (e.g., Supervisor).


Extension Points

  1. Custom Transports Implement BadPixxel\TaskingBundle\Transport\TransportInterface for new transports (e.g., Kafka, SQS).

  2. Task Middleware Add middleware to tasks via TaskMiddlewareInterface (e.g., logging, auth):

    badpixxel_tasking:
        middleware:
            - App\Middleware\LogTaskMiddleware
    
  3. Event Listeners Subscribe to task events (e.g., TaskStartedEvent, TaskFailedEvent):

    use BadPixxel\TaskingBundle\Event\TaskEvent;
    
    class MyListener
    {
        public function onTaskFailed(TaskEvent $event)
        {
            // Handle failure
        }
    }
    

    Register in services.yaml:

    services:
        App\Listener\MyListener:
            tags:
                - { name: 'kernel.event_listener', event: 'task.failed', method: 'onTaskFailed' }
    
  4. Custom Task Factories Override the default factory to

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui