Creating and Managing Active Jobs

Tutorial 2 of 5

Introduction

Goal

This tutorial aims to guide you through creating and managing Active Jobs in Rails. Active Job is a framework for declaring jobs that can be run in a variety of queuing backends. These jobs can be everything from regularly scheduled clean-ups to mailing customers when products come back in stock.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand what Active Jobs are and how they work in Rails.
- Create and manage Active Jobs.
- Use Active Job to manage background tasks in a standardized way.

Prerequisites

To follow along with this tutorial, you should have:
- A basic understanding of Ruby on Rails.
- Ruby on Rails installed on your machine.
- Basic knowledge of Ruby programming language.

Step-By-Step Guide

Active Job Basics

Active Job provides a framework for declaring jobs that are run in the background. It allows you to queue tasks (jobs) to be executed later, outside of the user's request-response cycle.

Creating an Active Job

To create a new Active Job, you can use the Rails generator:

rails generate job MyJob

This will create a file under app/jobs named my_job.rb.

Enqueueing Jobs

Jobs can be enqueued with perform_later method:

MyJob.perform_later

This will run the job as soon as the queuing system is free to do so.

Code Examples

Simple Active Job

Here's a simple example of an Active Job that sends an email:

class MyJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # Send an email
    UserMailer.with(user: User.first).welcome_email.deliver_now
  end
end

In this code:
- We define a new job named MyJob that inherits from ApplicationJob.
- We use queue_as to specify the queue's name.
- perform method contains the task to be done. In this case, send an email to the first user.

To enqueue this job, you would do:

MyJob.perform_later

This will add the job to the queue, and it will be executed as soon as possible.

Summary

In this tutorial, we've learned about Active Jobs in Rails, how to create them, and how to enqueue them. Active Jobs provide a way to handle background tasks that are outside of the immediate user's request-response cycle.

Next Steps

Continue to explore Active Job and its features. Try creating different jobs that perform various tasks.

Additional Resources

Practice Exercises

  1. Exercise 1: Create an Active Job that cleans up expired sessions from your database.
  2. Exercise 2: Create an Active Job that generates a weekly report and sends it via email.
  3. Exercise 3: Create an Active Job that resizes images uploaded by users.

For each exercise, you should:
- Define the job and the task it performs.
- Enqueue the job.
- Test the job to ensure it works as expected.

Remember, practice is key when it comes to coding. Happy coding!