This README outlines how to set up a basic Rails application with Resque for background jobs and Resque Scheduler for scheduling those jobs.
- Ruby 3.2.2
- Rails 7.x
- PostgreSQL (if running locally you will need to modify
config/database.yml
to use your local database) - Redis (if running locally you will need to modify
config/initializers/resque.rb
to use your local Redis server or you can modify theetc/hosts
file to pointredis
tolocalhost
)
rails new ResqueDemo --database=postgresql --css=tailwind
Add the following gems to your Gemfile
:
gem 'resque'
gem 'resque-scheduler'
Then run:
bundle install
Install Redis if you haven't:
brew install redis
Start Redis:
redis-server
Create an initializer at config/initializers/resque.rb
:
require 'resque'
require 'resque-scheduler'
require 'resque/scheduler/server'
In config/routes.rb
, add:
require 'resque/server'
Rails.application.routes.draw do
mount Resque::Server, at: "/resque"
end
Create a file app/jobs/example_job.rb
:
class ExampleJob
@queue = :example
def self.perform(name)
puts "Hello, #{name}"
end
end
Create a new file lib/tasks/resque.rake
:
namespace :resque do
task enqueue: :environment do
Resque.enqueue(ExampleJob, "Immediate")
end
task enqueue_in: :environment do
Resque.enqueue_in(5.seconds, ExampleJob, "In 5 seconds")
end
task enqueue_at: :environment do
time = Time.now + 1.minute
Resque.enqueue_at(time, ExampleJob, "At #{time}")
end
end
Create a config/resque_schedule.yml
:
ExampleJob:
cron: "* * * * *"
class: "ExampleJob"
args: "Loftwah"
description: "I'm an example job!"
NOTE: run
bin/setup
to set up the database and run migrations.
In separate terminals:
- Run Rails server:
rails server
- Run Resque worker:
QUEUE=* rake resque:work
- Run Resque scheduler:
rake resque:scheduler
OR
- Run
bin/setup
andbin/dev
to run all three in one terminal.
Run the custom rake tasks to enqueue jobs:
rake resque:enqueue
rake resque:enqueue_in
rake resque:enqueue_at
Docker has been set up to run the application and Redis. To run the application in Docker, run:
docker compose build
docker compose up
In another terminal run the following.
docker compose exec web rails db:setup
docker compose exec web rails db:migrate
Run the custom rake tasks to enqueue jobs:
docker compose exec web rake resque:enqueue
docker compose exec web rake resque:enqueue_in
docker compose exec web rake resque:enqueue_at
You can monitor the jobs at http://localhost:3000/resque
. Use port 3001
if running in Docker.