跳至內容 跳至搜尋

Active Job 基礎

Active Job 物件可設定為使用不同的後端排程架構。指定要使用的佇列轉接器

ActiveJob::Base.queue_adapter = :inline

可以在 QueueAdapters 中找到支援的轉接器清單。

Active Job 物件可透過建立繼承自 ActiveJob::Base 類別的類別來定義。唯一必要的實作方法是「執行」方法。

定義 Active Job 物件

class ProcessPhotoJob < ActiveJob::Base
  def perform(photo)
    photo.watermark!('Rails')
    photo.rotate!(90.degrees)
    photo.resize_to_fit!(300, 300)
    photo.upload!
  end
end

傳入的紀錄使用全域 ID 序列化 / 非序列化。更進一步的資訊可見 Arguments

在排程系統一有空閒就排入一個工作

ProcessPhotoJob.perform_later(photo)

在未來某個時段處理排程工作

ProcessPhotoJob.set(wait_until: Date.tomorrow.noon).perform_later(photo)

更進一步的資訊可見 ActiveJob::Core::ClassMethods#set

工作也可以立即處理,而無須傳送至佇列

ProcessPhotoJob.perform_now(photo)

例外

包含模組