How to Schedule Jobs in Rails: Simple Guide with Examples
In Rails, you schedule jobs by creating an
ActiveJob class and then using a scheduler like sidekiq-scheduler or whenever gem to run it at set times. You define the job's work in the job class and configure the scheduler to trigger it automatically.Syntax
To schedule a job in Rails, you first create a job class inheriting from ApplicationJob. Then you use a scheduler gem or system cron to run the job at specific times.
class MyJob < ApplicationJob: Defines the job class.performmethod: Contains the code to run.- Scheduler config: Defines when the job runs (e.g., every hour).
ruby
class MyJob < ApplicationJob queue_as :default def perform(*args) # Your task code here puts "Job is running" end end
Example
This example shows how to create a simple job and schedule it to run every minute using the sidekiq-scheduler gem.
ruby
# app/jobs/print_time_job.rb class PrintTimeJob < ApplicationJob queue_as :default def perform puts "Current time: #{Time.now}" end end # config/sidekiq.yml :schedule: print_time_job: cron: "* * * * *" # runs every minute class: "PrintTimeJob" # Run Sidekiq with scheduler enabled: # bundle exec sidekiq -C config/sidekiq.yml
Output
Current time: 2024-06-01 12:00:00 +0000
Current time: 2024-06-01 12:01:00 +0000
... (runs every minute)
Common Pitfalls
- Not setting up a background job processor like Sidekiq or Delayed Job, so scheduled jobs never run.
- Forgetting to configure the scheduler (cron or sidekiq-scheduler) properly.
- Running jobs synchronously in development without a queue, causing delays.
- Not setting the correct queue name or environment for the job.
ruby
# Wrong: Calling job perform method directly (runs immediately, no scheduling)
PrintTimeJob.new.perform
# Right: Enqueue job to run asynchronously
PrintTimeJob.perform_laterQuick Reference
Summary tips for scheduling jobs in Rails:
- Create job classes inheriting from
ApplicationJob. - Use
perform_laterto enqueue jobs asynchronously. - Choose a background processor like Sidekiq or Delayed Job.
- Use scheduler gems like
sidekiq-schedulerorwheneverfor timing. - Test jobs in development with
perform_nowif needed.
Key Takeaways
Create jobs by subclassing ApplicationJob and defining a perform method.
Use perform_later to enqueue jobs for background processing.
Configure a scheduler like sidekiq-scheduler or whenever to run jobs at set times.
Always run a background job processor (e.g., Sidekiq) to execute scheduled jobs.
Avoid calling perform directly to prevent blocking your app.