active_job_basics.md 11.3 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

3 4 5 6
Active Job Basics
=================

This guide provides you with all you need to get started in creating,
7
enqueuing and executing background jobs.
8 9 10 11 12 13

After reading this guide, you will know:

* How to create jobs.
* How to enqueue jobs.
* How to run jobs in the background.
14
* How to send emails from your application asynchronously.
15 16 17

--------------------------------------------------------------------------------

18

19 20 21 22
Introduction
------------

Active Job is a framework for declaring jobs and making them run on a variety
23
of queuing backends. These jobs can be everything from regularly scheduled
24
clean-ups, to billing charges, to mailings. Anything that can be chopped up
25 26 27
into small units of work and run in parallel, really.


28
The Purpose of Active Job
29 30
-----------------------------
The main point is to ensure that all Rails apps will have a job infrastructure
31 32 33 34 35 36
in place. We can then have framework features and other gems build on top of that,
without having to worry about API differences between various job runners such as
Delayed Job and Resque. Picking your queuing backend becomes more of an operational
concern, then. And you'll be able to switch between them without having to rewrite
your jobs.

37 38 39
NOTE: Rails by default comes with an asynchronous queuing implementation that
runs jobs with an in-process thread pool. Jobs will run asynchronously, but any
jobs in the queue will be dropped upon restart.
40 41 42 43 44


Creating a Job
--------------

45
This section will provide a step-by-step guide to creating a job and enqueuing it.
46 47 48

### Create the Job

C
Cristian Bica 已提交
49
Active Job provides a Rails generator to create jobs. The following will create a
50
job in `app/jobs` (with an attached test case under `test/jobs`):
C
Cristian Bica 已提交
51

52 53
```bash
$ bin/rails generate job guests_cleanup
54 55
invoke  test_unit
create    test/jobs/guests_cleanup_job_test.rb
56 57 58
create  app/jobs/guests_cleanup_job.rb
```

C
Cristian Bica 已提交
59 60 61 62 63 64 65
You can also create a job that will run on a specific queue:

```bash
$ bin/rails generate job guests_cleanup --queue urgent
```

If you don't want to use a generator, you could create your own file inside of
66
`app/jobs`, just make sure that it inherits from `ApplicationJob`.
67

68
Here's what a job looks like:
69 70

```ruby
71
class GuestsCleanupJob < ApplicationJob
72 73
  queue_as :default

74
  def perform(*guests)
75 76 77 78 79
    # Do something later
  end
end
```

80 81
Note that you can define `perform` with as many arguments as you want.

82 83 84 85 86
### Enqueue the Job

Enqueue a job like so:

```ruby
M
Mike Boone 已提交
87
# Enqueue a job to be performed as soon as the queuing system is
88
# free.
89
GuestsCleanupJob.perform_later guest
90 91 92
```

```ruby
93
# Enqueue a job to be performed tomorrow at noon.
94
GuestsCleanupJob.set(wait_until: Date.tomorrow.noon).perform_later(guest)
95 96 97
```

```ruby
98
# Enqueue a job to be performed 1 week from now.
99
GuestsCleanupJob.set(wait: 1.week).perform_later(guest)
100 101
```

102 103 104 105 106
```ruby
# `perform_now` and `perform_later` will call `perform` under the hood so
# you can pass as many arguments as defined in the latter.
GuestsCleanupJob.perform_later(guest1, guest2, filter: 'some_filter')
```
107

108
That's it!
109 110 111 112

Job Execution
-------------

113
For enqueuing and executing jobs in production you need to set up a queuing backend,
114 115 116
that is to say you need to decide for a 3rd-party queuing library that Rails should use.
Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM.
If the process crashes or the machine is reset, then all outstanding jobs are lost with the
117
default async backend. This may be fine for smaller apps or non-critical jobs, but most
118
production apps will need to pick a persistent backend.
119 120 121

### Backends

122
Active Job has built-in adapters for multiple queuing backends (Sidekiq,
123 124 125
Resque, Delayed Job and others). To get an up-to-date list of the adapters
see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html).

126
### Setting the Backend
127

128
You can easily set your queuing backend:
129 130

```ruby
131 132 133
# config/application.rb
module YourApp
  class Application < Rails::Application
134 135 136
    # Be sure to have the adapter's gem in your Gemfile
    # and follow the adapter's specific installation
    # and deployment instructions.
137 138 139
    config.active_job.queue_adapter = :sidekiq
  end
end
140 141
```

142 143 144
You can also configure your backend on a per job basis.

```ruby
145
class GuestsCleanupJob < ApplicationJob
146 147 148 149 150 151 152 153
  self.queue_adapter = :resque
  #....
end

# Now your job will use `resque` as it's backend queue adapter overriding what
# was configured in `config.active_job.queue_adapter`.
```

154 155 156
### Starting the Backend

Since jobs run in parallel to your Rails application, most queuing libraries
157
require that you start a library-specific queuing service (in addition to
158 159 160 161 162 163 164
starting your Rails app) for the job processing to work. Refer to library
documentation for instructions on starting your queue backend.

Here is a noncomprehensive list of documentation:

- [Sidekiq](https://github.com/mperham/sidekiq/wiki/Active-Job)
- [Resque](https://github.com/resque/resque/wiki/ActiveJob)
165
- [Sneakers](https://github.com/jondot/sneakers/wiki/How-To:-Rails-Background-Jobs-with-ActiveJob)
166 167
- [Sucker Punch](https://github.com/brandonhilkert/sucker_punch#active-job)
- [Queue Classic](https://github.com/QueueClassic/queue_classic#active-job)
168

169 170 171
Queues
------

172
Most of the adapters support multiple queues. With Active Job you can schedule
173
the job to run on a specific queue:
174 175

```ruby
176
class GuestsCleanupJob < ApplicationJob
177
  queue_as :low_priority
178 179 180 181
  #....
end
```

C
Cristian Bica 已提交
182
You can prefix the queue name for all your jobs using
183 184 185 186 187 188 189 190 191 192
`config.active_job.queue_name_prefix` in `application.rb`:

```ruby
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.active_job.queue_name_prefix = Rails.env
  end
end

M
Manu 已提交
193
# app/jobs/guests_cleanup_job.rb
194
class GuestsCleanupJob < ApplicationJob
195 196 197 198
  queue_as :low_priority
  #....
end

C
Cristian Bica 已提交
199
# Now your job will run on queue production_low_priority on your
200 201
# production environment and on staging_low_priority
# on your staging environment
202 203
```

204
The default queue name prefix delimiter is '\_'.  This can be changed by setting
205 206 207 208 209 210 211 212 213 214 215
`config.active_job.queue_name_delimiter` in `application.rb`:

```ruby
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.active_job.queue_name_prefix = Rails.env
    config.active_job.queue_name_delimiter = '.'
  end
end

M
Manu 已提交
216
# app/jobs/guests_cleanup_job.rb
217
class GuestsCleanupJob < ApplicationJob
218 219 220 221 222
  queue_as :low_priority
  #....
end

# Now your job will run on queue production.low_priority on your
223 224
# production environment and on staging.low_priority
# on your staging environment
225 226
```

227 228
If you want more control on what queue a job will be run you can pass a `:queue`
option to `#set`:
C
Cristian Bica 已提交
229 230 231 232 233

```ruby
MyJob.set(queue: :another_queue).perform_later(record)
```

234 235
To control the queue from the job level you can pass a block to `#queue_as`. The
block will be executed in the job context (so you can access `self.arguments`)
C
Cristian Bica 已提交
236 237 238
and you must return the queue name:

```ruby
239
class ProcessVideoJob < ApplicationJob
C
Cristian Bica 已提交
240 241 242 243 244 245 246 247 248 249
  queue_as do
    video = self.arguments.first
    if video.owner.premium?
      :premium_videojobs
    else
      :videojobs
    end
  end

  def perform(video)
250
    # Do process video
C
Cristian Bica 已提交
251 252 253 254 255 256
  end
end

ProcessVideoJob.perform_later(Video.last)
```

257
NOTE: Make sure your queuing backend "listens" on your queue name. For some
258
backends you need to specify the queues to listen to.
259 260 261 262 263


Callbacks
---------

264 265 266
Active Job provides hooks to trigger logic during the life cycle of a job. Like
other callbacks in Rails, you can implement the callbacks as ordinary methods
and use a macro-style class method to register them as callbacks:
267 268

```ruby
269
class GuestsCleanupJob < ApplicationJob
270 271
  queue_as :default

272
  around_perform :around_cleanup
273 274 275 276

  def perform
    # Do something later
  end
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

  private
    def around_cleanup(job)
      # Do something before perform
      yield
      # Do something after perform
    end
end
```

The macro-style class methods can also receive a block. Consider using this
style if the code inside your block is so short that it fits in a single line.
For example, you could send metrics for every job enqueued:

```ruby
class ApplicationJob
293
  before_enqueue { |job| $statsd.increment "#{job.name.underscore}.enqueue" }
294
end
295 296
```

297 298 299 300 301 302 303 304 305
### Available callbacks

* `before_enqueue`
* `around_enqueue`
* `after_enqueue`
* `before_perform`
* `around_perform`
* `after_perform`

306

G
Guo Xiang Tan 已提交
307
Action Mailer
308
------------
309

310 311
One of the most common jobs in a modern web application is sending emails outside
of the request-response cycle, so the user doesn't have to wait on it. Active Job
312
is integrated with Action Mailer so you can easily send emails asynchronously:
313 314

```ruby
315 316
# If you want to send the email now use #deliver_now
UserMailer.welcome(@user).deliver_now
317

X
Xavier Noria 已提交
318
# If you want to send the email through Active Job use #deliver_later
319
UserMailer.welcome(@user).deliver_later
320 321
```

S
Steven Chanin 已提交
322 323
NOTE: Using the asynchronous queue from a Rake task (for example, to
send an email using `.deliver_later`) will generally not work because Rake will
324 325
likely end, causing the in-process thread pool to be deleted, before any/all
of the `.deliver_later` emails are processed. To avoid this problem, use
S
Steven Chanin 已提交
326
`.deliver_now` or run a persistent queue in development.
327

328

J
Johannes Opper 已提交
329 330 331 332 333 334 335 336 337
Internationalization
--------------------

Each job uses the `I18n.locale` set when the job was created. Useful if you send
emails asynchronously:

```ruby
I18n.locale = :eo

M
Miguel Parramon 已提交
338
UserMailer.welcome(@user).deliver_later # Email will be localized to Esperanto.
J
Johannes Opper 已提交
339 340 341
```


342 343
GlobalID
--------
344

345 346 347
Active Job supports GlobalID for parameters. This makes it possible to pass live
Active Record objects to your job instead of class/id pairs, which you then have
to manually deserialize. Before, jobs would look like this:
348 349

```ruby
350
class TrashableCleanupJob < ApplicationJob
351 352 353 354 355 356 357 358 359 360
  def perform(trashable_class, trashable_id, depth)
    trashable = trashable_class.constantize.find(trashable_id)
    trashable.cleanup(depth)
  end
end
```

Now you can simply do:

```ruby
361
class TrashableCleanupJob < ApplicationJob
362 363 364 365 366 367
  def perform(trashable, depth)
    trashable.cleanup(depth)
  end
end
```

368
This works with any class that mixes in `GlobalID::Identification`, which
369
by default has been mixed into Active Record classes.
370 371 372 373


Exceptions
----------
374

375 376 377 378
Active Job provides a way to catch exceptions raised during the execution of the
job:

```ruby
379
class GuestsCleanupJob < ApplicationJob
380 381
  queue_as :default

382
  rescue_from(ActiveRecord::RecordNotFound) do |exception|
Y
Yauheni Dakuka 已提交
383
    # Do something with the exception
384 385 386 387 388 389 390
  end

  def perform
    # Do something later
  end
end
```
391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
### Retrying or Discarding failed jobs

It's also possible to retry or discard a job if an exception is raised during execution.
For example:

```ruby
class RemoteServiceJob < ActiveJob::Base
  retry_on CustomAppException # defaults to 3s wait, 5 attempts

  discard_on ActiveJob::DeserializationError

  def perform(*args)
    # Might raise CustomAppException or ActiveJob::DeserializationError
  end
end
```

To get more details see the API Documentation for [ActiveJob::Exceptions](http://api.rubyonrails.org/classes/ActiveJob/Exceptions/ClassMethods.html).

411 412 413 414 415 416 417
### Deserialization

GlobalID allows serializing full Active Record objects passed to `#perform`.

If a passed record is deleted after the job is enqueued but before the `#perform`
method is called Active Job will raise an `ActiveJob::DeserializationError`
exception.
418 419 420 421 422 423

Job Testing
--------------

You can find detailed instructions on how to test your jobs in the
[testing guide](testing.html#testing-jobs).