Creating Jobs
Basic Job Structure
# app/jobs/send_notification_job.py
import logging
from core.job import Job
logger = logging.getLogger("RouteMQ.Jobs.SendNotificationJob")
class SendNotificationJob(Job):
"""Send a notification to a user."""
# Job configuration
max_tries = 3 # Maximum retry attempts
timeout = 60 # Maximum seconds to run
retry_after = 10 # Seconds to wait before retry
queue = "default" # Queue name
def __init__(self):
super().__init__()
self.user_id = None
self.message = None
async def handle(self) -> None:
"""Execute the job."""
logger.info(f"Sending notification to user {self.user_id}")
logger.info(f"Message: {self.message}")
# Your notification logic here
# e.g., send push notification, SMS, email, etc.
logger.info("Notification sent successfully")
async def failed(self, exception: Exception) -> None:
"""Called when the job fails permanently."""
logger.error(
f"Failed to send notification to user {self.user_id}: {str(exception)}"
)
# Handle failure (e.g., log to monitoring service, alert admin)Job Properties
Property
Description
Default
Example
Custom Data in Jobs
Supported Data Types
The handle() Method
The failed() Method
Job Examples
Example 1: Email Job
Example 2: Data Processing Job
Example 3: Report Generation Job
Job Lifecycle
Best Practices
1. Keep Jobs Small and Focused
2. Make Jobs Idempotent
3. Set Appropriate Timeouts
4. Use Descriptive Class Names
5. Log Appropriately
Next Steps
Last updated