Skip to content

giljr/How_To_Use_Sidekiq

Repository files navigation

Working With Active Jobs - Sidekiq

Rails Active Job with Sidekiq & Redis - Step-by-Step

Here's a simplified project for setting up Active Jobs in Rails with Sidekiq and Redis, using sample models UserDetail and Employee.

1. Create a New Rails App

rails new active_jobs_demo
cd active_jobs_demo
code .

2. Add Required Gems

Add the following to your Gemfile:

gem 'sidekiq'
gem 'sidekiq-scheduler'
gem 'redis'

3. Install Gems

bundle install

4. Install Sidekiq Binstub

bundle binstubs sidekiq

5. Create Models

rails generate model UserDetail name:string profile:text
rails generate model Employee first_name:string last_name:string email:string notes:text

6. Add Validations

app/models/user_detail.rb

validates :name, presence: true, length: { minimum: 5, maximum: 15 }
validates :profile, presence: true

app/models/employee.rb

validates :first_name, :last_name, :email, presence: true
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }

Run the migration:

rails db:migrate

7. Seed Sample Data

Update db/seeds.rb with UserDetail and Employee records.

Important: Do not run rails db:seed yet.

8. Generate a Job

rails generate job update_employees

Edit app/jobs/update_employees_job.rb:

class UpdateEmployeesJob < ApplicationJob
  queue_as :default

  def perform(employee_id, attributes)
    employee = Employee.find(employee_id)
    employee.update(attributes)
  end
end

9. Trigger Job from Model

In app/models/employee.rb, update class:

class Employee < ApplicationRecord
  validates :first_name, :last_name, presence: true
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }

  after_create :update_employee
  after_update :update_employee

  def update_employee
    UpdateEmployeesJob.set(wait: 1.minutes).perform_later(self.id, {notes: "create notes from job"}) if saved_changes.key?(:created_at)
    UpdateEmployeesJob.set(queue: 'high_priority').perform_later(self.id, {notes: "update notes from job"}) if saved_changes.key?(:updated_at)
  end
end

10. Run Redis & Sidekiq

Start Redis:

redis-server

Start Sidekiq:

bundle exec sidekiq

11. Seed the Database

rails db:seed

Sidekiq will process background jobs as data is seeded.

12. Create Scheduled Job Without Model

Create a scheduled task with Sidekiq Scheduler:

config/sidekiq.yml

:queues:
  - critical
  - default
  - mailers

tasks: &tasks
  UpdateUsersJob:
    cron: "*/5 * * * *" # Every 5 minutes
    queue: default
    description: "Update User profile"

:scheduler:
  :schedule:
    <<: *tasks

13. Configure Redis

config/initializers/redis.rb

$redis = Redis.new(url: "redis://localhost:6379/0")

Sidekiq.configure_server do |config|
  config.redis = { url: "redis://localhost:6379/0" }
end

Sidekiq.configure_client do |config|
  config.redis = { url: "redis://localhost:6379/0" }
end

14. Load Sidekiq Scheduler

config/initializers/sidekiq.rb

require "sidekiq-scheduler"

15. Mount Sidekiq Web UI

config/routes.rb

require "sidekiq/web"

Rails.application.routes.draw do
  mount Sidekiq::Web => '/sidekiq'
  ...
end

16. Add Local Time Support

bin/importmap pin local-time

Then in config/importmap.rb:

pin "local-time"

And in app/javascript/application.js:

import LocalTime from "local-time"
LocalTime.start()

17. Add the Second Job

app/jobs/update_users_job.rb

class UpdateUsersJob < ApplicationJob
  queue_as :default

  def perform
    timestamp = Time.now.strftime('%B %e, %Y %l:%M %P')
    UserDetail.update_all(profile: "profile from job #{timestamp}")
  end
end

This job updates all UserDetail records every 5 minutes via Sidekiq Scheduler.

✅ Final Setup Summary

Models: UserDetail & Employee

Redis & Sidekiq: Fully configured

Job 1: UpdateEmployeesJob, triggered automatically on create/update

Job 2: UpdateUsersJob, runs every 5 minutes

🧹 How to Zero Sidekiq

To reset Sidekiq and clear job queues:

Option A - Clear All Redis Data

redis-cli flushall

⚠️ Warning: Deletes all Redis keys, including other apps.

Option B - Clear Only Current DB

redis-cli flushdb

Use this if you're not using the default Redis DB or sharing Redis across environments.

All done! We're here to bring you the best — every time! 🎉👏

Authors

@jaythree

Tutorial

Jungletronics

License

MIT

About

Working With Active Jobs - Sidekiq Rails Active Job with Sidekiq & Redis - Step-by-Step

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published