Rails Active Job #

一、Active Job概述 #

1.1 创建任务 #

bash
rails generate job Cleanup

1.2 任务定义 #

ruby
class CleanupJob < ApplicationJob
  queue_as :default
  
  def perform(*args)
    Article.where('created_at < ?', 1.year.ago).destroy_all
  end
end

二、执行任务 #

2.1 立即执行 #

ruby
CleanupJob.perform_later
CleanupJob.set(wait: 1.hour).perform_later

2.2 后端配置 #

ruby
# config/application.rb
config.active_job.queue_adapter = :sidekiq

三、总结 #

3.1 核心要点 #

要点 说明
ApplicationJob 任务基类
perform_later 异步执行
queue_as 队列名称

3.2 下一步 #

现在你已经掌握了Active Job,接下来让我们学习 Action Cable,深入了解Rails的实时通信!

最后更新:2026-03-28