Resque-AccessWorkerFromJob¶ ↑
Small plugin allowing the perform
method of Resque jobs to access the worker running them via the cleverly-named worker
instance variable.
Purpose: this allows jobs to access shared sockets in the parent worker, which I needed to implement a persistent TCP connection for sending background iPhone messages via Apple’s Push Notification Service.
As additional functionality, it can also abort a job gracefully if it’s picked up by the wrong worker class, which is useful if you’ve subclassed Resque::Worker to add your own functionality and need to ensure your jobs aren’t accidentally run against the original superclass.
Developed against Resque 1.8.0.
Usage¶ ↑
To use, add
extend Resque::Plugins::AccessWorkerFromJob
to the bottom of the class with the perform method (the extend line must come after the perform method has already been defined, or else the alias method will fail). Now your perform method can reference a worker
attribute.
Example:
class MessageJob @queue = :messages # Example using shared socket from worker (via @worker or self.worker) def self.perform( msg ) worker.socket.write( msg ) end extend Resque::Plugins::AccessWorkerFromJob self.required_worker_class = 'CustomApplication::MessageSender' end
To implement the additional abort-if-picked-up-by-wrong-worker-class feature, add
self.required_worker_class = 'ClassName'
as well.
Warnings¶ ↑
Ephemeral nature of worker changes¶ ↑
Be careful to note that each job forks before running, so instance variables will be a copy and, if changed, their changes won’t persist into the next job’s perform method. However, since sockets ARE persisted, this allows multiple jobs to share a single persistent socket kept alive in the worker.
Copyright¶ ↑
Copyright © 2010 Kali Donovan. See LICENSE for details.