|
| 1 | +Resque Plugins |
| 2 | +============== |
| 3 | + |
| 4 | +Resque encourages plugin development. In most cases, customize your |
| 5 | +environment with a plugin rather than adding to the core. |
| 6 | + |
| 7 | +Hooks |
| 8 | +----- |
| 9 | + |
| 10 | +Plugins can utilize job hooks to provide additional behavior. The available |
| 11 | +hooks are: |
| 12 | + |
| 13 | +* `before_perform`: Called with the job args before perform. If it raises |
| 14 | + Resque::Job::DontPerform, the job is aborted. If other exceptions are |
| 15 | + raised, they will be propagated up the the `Resque::Failure` backend. |
| 16 | + |
| 17 | +* `after_perform`: Called with the job args after it performs. Uncaught |
| 18 | + exceptions will propagate up to the `Resque::Failure` backend. |
| 19 | + |
| 20 | +* `around_perform`: Called with the job args. It is expected to yield in order |
| 21 | + to perform the job (but is not required to do so). It may handle exceptions |
| 22 | + thrown by `perform`, but any that are not caught will propagate up to the |
| 23 | + `Resque::Failure` backend. |
| 24 | + |
| 25 | +* `on_failure`: Called with the exception and job args if any exception occurs |
| 26 | + while performing the job (or hooks). |
| 27 | + |
| 28 | +Hooks are easily implemented with superclasses or modules. A superclass could |
| 29 | +look something like this. |
| 30 | + |
| 31 | + class LoggedJob |
| 32 | + def self.before_perform(*args) |
| 33 | + Logger.info "About to perform #{self} with #{args.inspect}" |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + class MyJob < LoggedJob |
| 38 | + def self.perform(*args) |
| 39 | + ... |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | +Modules are even better because jobs can use many of them. |
| 44 | + |
| 45 | + module LoggedJob |
| 46 | + def before_perform(*args) |
| 47 | + Logger.info "About to perform #{self} with #{args.inspect}" |
| 48 | + end |
| 49 | + end |
| 50 | + |
| 51 | + module RetriedJob |
| 52 | + def on_failure(e, *args) |
| 53 | + Logger.info "Performing #{self} caused an exception (#{e.inspect}). Retrying..." |
| 54 | + Resque.enqueue self, *args |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + class MyJob |
| 59 | + extend LoggedJob |
| 60 | + extend RetriedJob |
| 61 | + def self.perform(*args) |
| 62 | + ... |
| 63 | + end |
| 64 | + end |
| 65 | + |
0 commit comments