# Active Job 异步任务

异步适配器，统一接口。有队列 Queue，有任务 Job 等相关概念及其它方法。

Web 开发过程中，会遇到很多需要异步处理的任务：发邮件、发短信、图片处理、下载东西、spam 检测等。一般来说，这样的程序执行时间长，并且不需要实时把结果反馈给用户。我们可以将这些处理时间长的请求剥离出来异步处理，并及时响应页面的请求。

市面上已经有不少和这有关的 gem，它们封装好了接口，我们直接调用即可，比如受到广泛使用的 Resque、Sidekiq、Delayed job 等。

这些 gem 做的事情都大同小异，但特性上却各自不同：

|             | 异步 | 队列 | 延时(定时)  | 优先级 | 超时 | 重试 |
| ----------- | -- | -- | ------- | --- | -- | -- |
| Delayed Job | 是  | 是  | 是       | 任务  | 全局 | 全局 |
| Resque      | 是  | 是  | 是 (Gem) | 队列  | 全局 | 是  |
| Sidekiq     | 是  | 是  | 是       | 队列  | 否  | 任务 |

并且，在实际使用过程中，你会关心性能怎么样、是否支持多线程、持久化方案，以及 API 使用难易程度、稳定性等问题。也就是说，你有可能要更改异步处理所使用的 gem.

必要的话，你要快速切换到另一种异步处理方案上。更进一步，你不想被绑在一颗树上，不想每换一种方案都学习其专有的语法。

Active Job 解决了这个问题，它统一了接口，做到了：**不同的延迟任务，一样的 API.** Active Job 本身并不提供真正的后端任务解决方案，它做的主要是适配，你可以选择使用自己需要的方案，并且以后可以迁移到其它方案。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kelby.gitbook.io/rails-beginner-s-guide/activejob.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
