Job creation and queuing lets your app do tasks in the background. This keeps your app fast and smooth for users.
0
0
Job creation and queuing in Ruby on Rails
Introduction
Sending emails after a user signs up without making them wait
Processing uploaded images or files without slowing the app
Running long calculations or reports without freezing the page
Cleaning up old data regularly without interrupting users
Calling external services that might be slow or unreliable
Syntax
Ruby on Rails
class MyJob < ApplicationJob queue_as :default def perform(*args) # Do the work here end end # To enqueue the job: MyJob.perform_later(arguments)
Jobs are Ruby classes that inherit from ApplicationJob.
Use perform_later to add the job to the queue.
Examples
This job sends a welcome email to a user with ID 42 in the background.
Ruby on Rails
class EmailJob < ApplicationJob queue_as :mailers def perform(user_id) user = User.find(user_id) UserMailer.welcome_email(user).deliver_now end end EmailJob.perform_later(42)
This job deletes old records without blocking the app.
Ruby on Rails
class CleanupJob < ApplicationJob queue_as :default def perform OldRecord.where('created_at < ?', 1.month.ago).delete_all end end CleanupJob.perform_later
Sample Program
This job prints a greeting message in the background. When run, it will output the greeting without blocking the main app.
Ruby on Rails
class GreetingJob < ApplicationJob queue_as :default def perform(name) puts "Hello, #{name}!" end end # Enqueue the job GreetingJob.perform_later('Alice')
OutputSuccess
Important Notes
Make sure you have a queue adapter set up (like Sidekiq or the default async adapter) to run jobs.
Jobs run outside the main web request, so they won't slow down user actions.
You can set different queues to prioritize important jobs.
Summary
Jobs let you run tasks in the background to keep your app fast.
Create jobs by inheriting from ApplicationJob and defining a perform method.
Use perform_later to add jobs to the queue for later execution.