Dispatching Jobs

Once you've created a job, you need to dispatch it to the queue for processing. RouteMQ provides several methods for dispatching jobs.

Using the dispatch() Helper

The simplest way to dispatch a job:

from core.queue.queue_manager import dispatch
from app.jobs.send_notification_job import SendNotificationJob

# In your MQTT handler or anywhere in your code
async def handle_message(context):
    # Create and configure the job
    job = SendNotificationJob()
    job.user_id = 123
    job.message = "Your order has been shipped!"

    # Dispatch to queue
    await dispatch(job)

The dispatch() helper:

  • Uses the queue specified in the job (job.queue)

  • Uses the default connection from .env

  • Returns immediately after pushing to queue

Using the Queue Manager

For more control, use the QueueManager directly:

Delayed Jobs

Schedule a job to run after a delay:

How delayed jobs work:

  • Job is stored with an available_at timestamp

  • Worker ignores the job until the timestamp is reached

  • Redis uses sorted sets for efficient delay handling

  • Database uses datetime comparison

Bulk Dispatching

Dispatch multiple jobs at once:

This is more efficient than dispatching jobs one by one in a loop.

Dispatching from MQTT Handlers

Example 1: Dispatch from Controller

Example 2: Dispatch with Middleware

Example 3: Conditional Dispatching

Checking Queue Size

Monitor how many jobs are pending:

Queue Manager API Reference

push()

Push a job to the queue immediately.

later()

Push a job with a delay.

bulk()

Push multiple jobs at once.

size()

Get the number of pending jobs in a queue.

Common Patterns

Pattern 1: Fan-out

Dispatch multiple jobs from one event:

Pattern 2: Delayed Chain

Schedule a series of jobs:

Pattern 3: Priority Queues

Use different queues for different priorities:

Then run workers with appropriate settings:

Pattern 4: Rate Limiting

Prevent overwhelming external services:

Error Handling

Handle Dispatch Errors

Verify Job Data

Best Practices

1. Dispatch Early, Process Later

2. Don't Dispatch Too Much Data

3. Use Appropriate Delays

4. Choose the Right Queue

Next Steps

Last updated