Background jobs & scheduled cron jobs
RailsFast comes with a robust background job processing system using Solid Queue, Rails 8's built-in job backend.
This is a fully-functional, production-ready background job system that allows you to:
- Offload long-running operations (like processing files, or running cleanup tasks) as background jobs to be performed asynchronously in the background whenever the system can
- Enqueue jobs to be performed later, in 5 minutes or any arbitrary amount of time
- Send emails / do things whithout blocking the current request and making the user feel wait time
- Handle file uploads and processing
- Schedule jobs to run at night or whenever you'd like (
cron-like), very useful for admin and reporting tasks - Handle retries automatically, retry jobs multiple times if they fail
Something people don't usually expect is that this entire system doesn't have any dependency on Redis! You don't need any Redis process, instance or any in-memory store system to run this, it's all database-backed! (and very efficient in production!)
Creating a background job
It's better you read the ActiveJob docs, but in a nutshell, you generate a new job with:
rails generate job SendWelcomeEmail
Which creates the job file:
# app/jobs/send_welcome_email_job.rb
class SendWelcomeEmailJob < ApplicationJob
queue_as :default
def perform(user)
UserMailer.welcome_email(user).deliver_now
end
end
And then you can either perform the job right now:
SendWelcomeEmailJob.perform_later(current_user)
Or perform it later:
# Perform in 5 minutes
SendWelcomeEmailJob.set(wait: 5.minutes).perform_later(current_user)
# Perform at specific time
SendWelcomeEmailJob.set(wait_until: Date.tomorrow.noon).perform_later(current_user)
Schedule recurring jobs (cron-like)
You can schedule recurring jobs, which behave pretty much like cron behaves. To see all your recurring jobs and edit when they get triggered, open your config/recurring.yml file:
production:
refresh_sitemap:
class: SitemapRefreshJob
queue: default
schedule: every day at 4am Europe/Lisbon
Refer to the ActiveJob docs to learn how to handle job errors and retries.
Web UI
As mentioned in the Admin section, RailsFast comes with a dashboard to see all your background tasks, all your scheduled task and when they last ran, the output and result of each job run, etc. You can also discard and retry jobs manually. Access it as an admin user via /admin/jobs