rails-active-job

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Active Job: Background Job Processing

Active Job:后台任务处理

Active Job is Rails' framework for declaring background jobs and processing them asynchronously. Use it to offload work from the request-response cycle, improving application responsiveness.
Active Job是Rails的一款框架,用于声明后台任务并异步处理它们。使用它可以将工作从请求-响应周期中卸载,提升应用的响应速度。

When to Use Active Jobs

何时使用Active Job

  • Email sending: Async mailers to avoid request delays
  • Heavy computations: Process data without blocking users
  • External API calls: Retry logic for unreliable services
  • Bulk operations: Process large datasets in the background
  • Scheduled tasks: Recurring operations with cron jobs
  • Event processing: Handle webhooks and event notifications
  • Cleanup tasks: Database maintenance and data archival
  • 邮件发送:使用异步邮件发送器避免请求延迟
  • 繁重计算:处理数据时不阻塞用户操作
  • 外部API调用:为不可靠服务添加重试逻辑
  • 批量操作:在后台处理大型数据集
  • 调度任务:使用定时任务执行周期性操作
  • 事件处理:处理Webhook和事件通知
  • 清理任务:数据库维护和数据归档

Quick Start

快速开始

Create a Job

创建任务

bash
rails generate job SendWelcomeEmail
bash
rails generate job SendWelcomeEmail

Define the Job

定义任务

ruby
class SendWelcomeEmailJob < ApplicationJob
  queue_as :default  # Route to 'default' queue
  
  def perform(user_id)
    user = User.find(user_id)
    UserMailer.welcome(user).deliver_later
  end
end
ruby
class SendWelcomeEmailJob < ApplicationJob
  queue_as :default  # 路由到'default'队列
  
  def perform(user_id)
    user = User.find(user_id)
    UserMailer.welcome(user).deliver_later
  end
end

Enqueue the Job

将任务加入队列

ruby
undefined
ruby
undefined

Enqueue immediately

立即加入队列

SendWelcomeEmailJob.perform_later(user.id)
SendWelcomeEmailJob.perform_later(user.id)

Enqueue with delay

延迟加入队列

SendWelcomeEmailJob.set(wait: 1.hour).perform_later(user.id)
SendWelcomeEmailJob.set(wait: 1.hour).perform_later(user.id)

Enqueue at specific time

在指定时间加入队列

SendWelcomeEmailJob.set(wait_until: 2.days.from_now).perform_later(user.id)
SendWelcomeEmailJob.set(wait_until: 2.days.from_now).perform_later(user.id)

Enqueue multiple jobs at once

批量加入多个任务

user_ids.map { |id| [id] }.then do |args| SendWelcomeEmailJob.perform_all_later(args) end
undefined
user_ids.map { |id| [id] }.then do |args| SendWelcomeEmailJob.perform_all_later(args) end
undefined

Job Basics

任务基础

Learn fundamental job concepts and lifecycle:
  • Job Definition — Job structure, configuration, perform method
  • Job Lifecycle — Job execution phases and callbacks
  • Job Patterns — Common implementations and best practices
了解核心的任务概念与生命周期:
  • 任务定义 — 任务结构、配置、perform方法
  • 任务生命周期 — 任务执行阶段与回调
  • 任务模式 — 常见实现方式与最佳实践

Queue Management

队列管理

Configure and manage job queues:
  • Queue Setup — Solid Queue configuration, threading, queue ordering
  • Concurrency Controls — Limit concurrent job execution
配置并管理任务队列:
  • 队列设置 — Solid Queue配置、线程、队列排序
  • 并发控制 — 限制任务并发执行

Advanced Features

高级功能

Master sophisticated job patterns:
  • Scheduling & Retries — Recurring jobs, retry strategies, backoff
  • Error Handling — Exception handling, discard policies, dead letter queues
  • Job Continuations — Multi-step resumable workflows (Rails 8+)
  • Bulk Enqueuing — Efficient batch job enqueueing
  • Testing — Test job enqueuing and execution
掌握复杂的任务模式:
  • 调度与重试 — 周期性任务、重试策略、退避机制
  • 错误处理 — 异常处理、丢弃策略、死信队列
  • 任务续传 — 多步骤可恢复工作流(Rails 8+)
  • 批量入队 — 高效的批量任务入队方式
  • 测试 — 测试任务入队与执行

Examples

示例

See Real-world implementations covering:
  • Email notifications
  • Data imports and exports
  • Image processing
  • External API synchronization
  • Report generation
  • Webhook handling
查看真实场景实现,涵盖:
  • 邮件通知
  • 数据导入与导出
  • 图片处理
  • 外部API同步
  • 报表生成
  • Webhook处理

Default Backend: Solid Queue

默认后端:Solid Queue

Rails 8+ includes Solid Queue as the default job backend. Configure in
config/solid_queue.yml
:
yaml
production:
  queues:
    - name: default
      threads: 5
    - name: critical
      threads: 2
    - name: batch
      threads: 1
  
  workers:
    - name: worker_1
      queues: [ default, critical, batch ]
  
  scheduler:
    workers: 1
Solid Queue provides:
  • Database-backed job storage (no additional dependencies)
  • Queue ordering and priority
  • Concurrency limiting
  • Repeating jobs (cron-like scheduling)
  • Multi-threaded workers
  • Built-in error tracking
Rails 8+将Solid Queue作为默认任务后端。在
config/solid_queue.yml
中配置:
yaml
production:
  queues:
    - name: default
      threads: 5
    - name: critical
      threads: 2
    - name: batch
      threads: 1
  
  workers:
    - name: worker_1
      queues: [ default, critical, batch ]
  
  scheduler:
    workers: 1
Solid Queue提供:
  • 基于数据库的任务存储(无需额外依赖)
  • 队列排序与优先级
  • 并发限制
  • 重复任务(类定时任务调度)
  • 多线程工作进程
  • 内置错误追踪

Key Concepts

核心概念

ConceptDescription
JobRuby class defining async work (inherits from ApplicationJob)
QueueNamed container for jobs (default, critical, batch, etc.)
EnqueueAdd job to queue for processing (perform_later)
WorkerProcess that executes jobs from queues
RetryAutomatic job re-execution after failure
DiscardPermanently skip job after error
ContinuationResume job execution in steps (Rails 8+)
概念描述
Job(任务)定义异步工作的Ruby类(继承自ApplicationJob)
Queue(队列)任务的命名容器(如default、critical、batch等)
Enqueue(入队)将任务加入队列等待执行(perform_later方法)
Worker(工作进程)从队列中取出并执行任务的进程
Retry(重试)任务失败后自动重新执行
Discard(丢弃)任务出错后永久跳过
Continuation(续传)分步骤恢复任务执行(Rails 8+)

Next Steps

后续步骤

  1. Start with Job Definition to understand job structure
  2. Configure Queue Setup for your environment
  3. Add Error Handling for reliability
  4. Learn Testing strategies for your jobs
  5. Explore Examples for your use case
  1. 任务定义开始,了解任务结构
  2. 为你的环境配置队列设置
  3. 添加错误处理提升可靠性
  4. 学习任务的测试策略
  5. 根据你的使用场景探索示例

Resources

资源