0
0
Ruby on Railsframework~5 mins

Scheduled jobs in Ruby on Rails

Choose your learning style9 modes available
Introduction

Scheduled jobs let your app do tasks automatically at set times. This helps with things like sending emails or cleaning up data without you doing it manually.

Send daily reminder emails to users at 9 AM.
Clean up old temporary files every night.
Generate weekly reports every Monday morning.
Sync data with an external service every hour.
Syntax
Ruby on Rails
class MyJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # task code here
  end
end

# To schedule, use a scheduler like 'whenever' gem or Active Job with cron
# Example with 'whenever' gem in schedule.rb:
every 1.day, at: '9:00 am' do
  runner "MyJob.perform_later"
end

Jobs are classes inheriting from ApplicationJob.

Use a scheduler gem like whenever or system cron to run jobs at set times.

Examples
This job deletes old temporary files when run.
Ruby on Rails
class CleanupJob < ApplicationJob
  queue_as :default

  def perform
    TempFile.delete_old_files
  end
end
This whenever schedule runs a sync method every hour.
Ruby on Rails
every 1.hour do
  runner "SyncService.sync_data"
end
This job sends a reminder email to a specific user.
Ruby on Rails
class ReminderJob < ApplicationJob
  queue_as :default

  def perform(user_id)
    user = User.find(user_id)
    UserMailer.reminder_email(user).deliver_now
  end
end
Sample Program

This simple job prints a greeting message with the given name. We run it immediately to see the output.

Ruby on Rails
class GreetJob < ApplicationJob
  queue_as :default

  def perform(name)
    puts "Hello, #{name}! This job ran successfully."
  end
end

# Simulate running the job immediately
GreetJob.perform_now('Alice')
OutputSuccess
Important Notes

Scheduled jobs run in the background, so they don't slow down your app's main work.

Use perform_later to run jobs asynchronously, and perform_now for immediate execution (usually in tests).

Make sure your scheduler (like cron or whenever) is properly set up on your server to trigger jobs on time.

Summary

Scheduled jobs automate tasks to run at specific times without manual effort.

Define jobs by creating classes inheriting from ApplicationJob.

Use scheduling tools like whenever gem or cron to run jobs regularly.