Rails Resque Ioerror: Not Opened for Reading
Active Job Basics
This guide provides you with all you demand to get started in creating, enqueuing and executing groundwork jobs.
Later on reading this guide, you will know:
- How to create jobs.
- How to enqueue jobs.
- How to run jobs in the groundwork.
- How to send emails from your application asynchronously.
Chapters
- What is Agile Job?
- The Purpose of Active Job
- Creating a Job
- Create the Job
- Enqueue the Job
- Job Execution
- Backends
- Setting the Backend
- Starting the Backend
- Queues
- Callbacks
- Available callbacks
- Activity Mailer
- Internationalization
- Supported types for arguments
- GlobalID
- Serializers
- Exceptions
- Retrying or Discarding failed jobs
- Deserialization
- Task Testing
i What is Active Job?
Agile Job is a framework for declaring jobs and making them run on a variety of queuing backends. These jobs tin be everything from regularly scheduled make clean-ups, to billing charges, to mailings. Annihilation that tin be chopped up into small units of piece of work and run in parallel, really.
2 The Purpose of Agile Task
The main bespeak is to ensure that all Rail apps will have a job infrastructure in place. Nosotros can then have framework features and other gems build on acme 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 business organisation, and so. And you'll exist able to switch between them without having to rewrite your jobs.
Runway by default comes with an asynchronous queuing implementation that runs jobs with an in-process thread pool. Jobs volition run asynchronously, but whatsoever jobs in the queue will exist dropped upon restart.
3 Creating a Chore
This section will provide a step-past-stride guide to creating a job and enqueuing it.
3.1 Create the Job
Active Chore provides a Track generator to create jobs. The following volition create a task in app/jobs
(with an attached test case under test/jobs
):
$ bin/rails generate job guests_cleanup invoke test_unit create test/jobs/guests_cleanup_job_test.rb create app/jobs/guests_cleanup_job.rb
You tin can also create a task that will run on a specific queue:
$ bin/rails generate job guests_cleanup --queue urgent
If you don't desire to use a generator, you could create your own file inside of app/jobs
, only make sure that information technology inherits from ApplicationJob
.
Here's what a job looks like:
class GuestsCleanupJob < ApplicationJob queue_as :default def perform ( * guests ) # Do something afterward finish end
Note that you can ascertain perform
with every bit many arguments every bit you desire.
3.2 Enqueue the Job
Enqueue a task using perform_later
and, optionally, ready
. Like and then:
# Enqueue a job to be performed as soon every bit the queuing system is # gratis. GuestsCleanupJob . perform_later guest
# Enqueue a job to be performed tomorrow at noon. GuestsCleanupJob . set ( wait_until: Date . tomorrow . noon ). perform_later ( guest )
# Enqueue a job to be performed ane week from now. GuestsCleanupJob . ready ( look: one . calendar week ). perform_later ( guest )
# `perform_now` and `perform_later` volition 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' )
That's information technology!
4 Job Execution
For enqueuing and executing jobs in production you need to set a queuing backend, that is to say, y'all need to decide on a third-party queuing library that Rails should use. Rails itself but provides an in-process queuing system, which just keeps the jobs in RAM. If the process crashes or the automobile is reset, and then all outstanding jobs are lost with the default async backend. This may exist fine for smaller apps or non-disquisitional jobs, just about production apps volition need to selection a persistent backend.
4.i Backends
Active Task has built-in adapters for multiple queuing backends (Sidekiq, Resque, Delayed Job, and others). To get an up-to-date list of the adapters see the API Documentation for ActiveJob::QueueAdapters
.
4.ii Setting the Backend
You lot can easily gear up your queuing backend with config.active_job.queue_adapter
:
# config/application.rb module YourApp class Application < Rails :: Application # Be certain to accept the adapter'southward precious stone in your Gemfile # and follow the adapter'south specific installation # and deployment instructions. config . active_job . queue_adapter = :sidekiq stop finish
You can also configure your backend on a per job footing:
class GuestsCleanupJob < ApplicationJob cocky . queue_adapter = :resque # ... end # Now your chore will apply `resque` as its backend queue adapter, overriding what # was configured in `config.active_job.queue_adapter`.
4.3 Starting the Backend
Since jobs run in parallel to your Rails application, most queuing libraries require that you start a library-specific queuing service (in addition to starting your Runway app) for the chore processing to work. Refer to library documentation for instructions on starting your queue backend.
Here is a noncomprehensive list of documentation:
- Sidekiq
- Resque
- Sneakers
- Sucker Punch
- Queue Classic
- Delayed Job
- Que
- Good Task
5 Queues
Most of the adapters back up multiple queues. With Active Job you tin can schedule the chore to run on a specific queue using queue_as
:
class GuestsCleanupJob < ApplicationJob queue_as :low_priority # ... end
Y'all can prefix the queue proper noun for all your jobs using config.active_job.queue_name_prefix
in application.rb
:
# config/awarding.rb module YourApp form Awarding < Rails :: Awarding config . active_job . queue_name_prefix = Runway . env end end
# app/jobs/guests_cleanup_job.rb class GuestsCleanupJob < ApplicationJob queue_as :low_priority # ... end # Now your task will run on queue production_low_priority on your # production environment and on staging_low_priority # on your staging environment
Yous can also configure the prefix on a per job basis.
course GuestsCleanupJob < ApplicationJob queue_as :low_priority cocky . queue_name_prefix = nil # ... end # Now your job'southward queue won't be prefixed, overriding what # was configured in `config.active_job.queue_name_prefix`.
The default queue proper noun prefix delimiter is '_'. This can be inverse by setting config.active_job.queue_name_delimiter
in awarding.rb
:
# config/awarding.rb module YourApp class Application < Rails :: Application config . active_job . queue_name_prefix = Rail . env config . active_job . queue_name_delimiter = '.' stop finish
# app/jobs/guests_cleanup_job.rb class GuestsCleanupJob < ApplicationJob queue_as :low_priority # ... end # At present your chore volition run on queue production.low_priority on your # production environment and on staging.low_priority # on your staging environs
If you want more control on what queue a job volition be run you can pass a :queue
option to set
:
MyJob . set ( queue: :another_queue ). perform_later ( record )
To control the queue from the chore level you tin pass a cake to queue_as
. The block will be executed in the chore context (so it tin access self.arguments
), and it must return the queue name:
class ProcessVideoJob < ApplicationJob queue_as practise video = self . arguments . commencement if video . owner . premium? :premium_videojobs else :videojobs end end def perform ( video ) # Do process video end cease
ProcessVideoJob . perform_later ( Video . last )
Make sure your queuing backend "listens" on your queue proper name. For some backends y'all demand to specify the queues to heed to.
6 Callbacks
Active Job provides hooks to trigger logic during the life bicycle of a job. Similar other callbacks in Rail, you lot can implement the callbacks as ordinary methods and utilise a macro-mode class method to register them as callbacks:
class GuestsCleanupJob < ApplicationJob queue_as :default around_perform :around_cleanup def perform # Practice something later finish individual def around_cleanup # Do something earlier perform yield # Practice something after perform end end
The macro-style course methods can also receive a block. Consider using this style if the code inside your block is and then short that information technology fits in a single line. For example, you lot could send metrics for every job enqueued:
class ApplicationJob < ActiveJob :: Base of operations before_enqueue { | job | $statsd . increment " #{ job . class . name . underscore } .enqueue" } terminate
6.1 Available callbacks
-
before_enqueue
-
around_enqueue
-
after_enqueue
-
before_perform
-
around_perform
-
after_perform
7 Action Mailer
1 of the most common jobs in a modern web application is sending emails outside of the asking-response cycle, so the user doesn't have to wait on it. Active Job is integrated with Action Mailer then yous can easily ship emails asynchronously:
# If y'all want to send the email now apply #deliver_now UserMailer . welcome ( @user ). deliver_now # If you desire to ship the e-mail through Agile Chore utilize #deliver_later UserMailer . welcome ( @user ). deliver_later
Using the asynchronous queue from a Rake chore (for example, to send an email using .deliver_later
) will generally not work because Rake will likely end, causing the in-procedure thread puddle to be deleted, before any/all of the .deliver_later
emails are processed. To avoid this problem, use .deliver_now
or run a persistent queue in development.
8 Internationalization
Each job uses the I18n.locale
ready when the chore was created. This is useful if y'all transport emails asynchronously:
I18n . locale = :eo UserMailer . welcome ( @user ). deliver_later # Electronic mail will be localized to Esperanto.
ix Supported types for arguments
ActiveJob supports the following types of arguments by default:
- Basic types (
NilClass
,String
,Integer
,Float
,BigDecimal
,TrueClass
,FalseClass
) -
Symbol
-
Date
-
Fourth dimension
-
DateTime
-
ActiveSupport::TimeWithZone
-
ActiveSupport::Duration
-
Hash
(Keys should be ofString
orSymbol
blazon) -
ActiveSupport::HashWithIndifferentAccess
-
Assortment
-
Range
-
Module
-
Class
9.one GlobalID
Agile Job supports GlobalID for parameters. This makes it possible to laissez passer alive Active Record objects to your job instead of class/id pairs, which you and then have to manually deserialize. Before, jobs would look like this:
class TrashableCleanupJob < ApplicationJob def perform ( trashable_class , trashable_id , depth ) trashable = trashable_class . constantize . find ( trashable_id ) trashable . cleanup ( depth ) terminate terminate
Now you tin can simply do:
class TrashableCleanupJob < ApplicationJob def perform ( trashable , depth ) trashable . cleanup ( depth ) stop stop
This works with any class that mixes in GlobalID::Identification
, which by default has been mixed into Active Tape classes.
9.2 Serializers
You can extend the list of supported argument types. You just need to define your own serializer:
# app/serializers/money_serializer.rb class MoneySerializer < ActiveJob :: Serializers :: ObjectSerializer # Checks if an argument should be serialized by this serializer. def serialize? ( statement ) argument . is_a? Money end # Converts an object to a simpler representative using supported object types. # The recommended representative is a Hash with a specific cardinal. Keys tin be of basic types only. # You should phone call `super` to add the custom serializer type to the hash. def serialize ( coin ) super ( "corporeality" => coin . amount , "currency" => coin . currency ) end # Converts serialized value into a proper object. def deserialize ( hash ) Money . new ( hash [ "amount" ], hash [ "currency" ]) end end
and add this serializer to the list:
# config/initializers/custom_serializers.rb Rails . application . config . active_job . custom_serializers << MoneySerializer
Notation that autoloading reloadable lawmaking during initialization is not supported. Thus information technology is recommended to set-upwardly serializers to be loaded but in one case, due east.g. by amending config/application.rb
similar this:
# config/application.rb module YourApp class Awarding < Rails :: Application config . autoload_once_paths << Rails . root . bring together ( 'app' , 'serializers' ) end finish
10 Exceptions
Exceptions raised during the execution of the job can exist handled with rescue_from
:
class GuestsCleanupJob < ApplicationJob queue_as :default rescue_from ( ActiveRecord :: RecordNotFound ) practice | exception | # Do something with the exception end def perform # Practice something subsequently end cease
If an exception from a job is not rescued, so the job is referred to as "failed".
x.one Retrying or Discarding failed jobs
A failed chore volition not be retried, unless configured otherwise.
It'southward possible to retry or discard a failed job by using retry_on
or discard_on
, respectively. For instance:
grade RemoteServiceJob < ApplicationJob retry_on CustomAppException # defaults to 3s wait, 5 attempts discard_on ActiveJob :: DeserializationError def perform ( * args ) # Might raise CustomAppException or ActiveJob::DeserializationError cease end
10.2 Deserialization
GlobalID allows serializing full Active Tape objects passed to #perform
.
If a passed record is deleted after the job is enqueued but before the #perform
method is chosen Active Job will raise an ActiveJob::DeserializationError
exception.
11 Job Testing
You can find detailed instructions on how to exam your jobs in the testing guide.
Feedback
You're encouraged to assistance ameliorate the quality of this guide.
Please contribute if you see any typos or factual errors. To become started, y'all can read our documentation contributions section.
Y'all may besides discover incomplete content or stuff that is not up to date. Please do add any missing documentation for primary. Make sure to check Edge Guides kickoff to verify if the issues are already fixed or not on the main branch. Bank check the Cerise on Rails Guides Guidelines for way and conventions.
If for whatever reason y'all spot something to fix simply cannot patch information technology yourself, please open an issue.
And last but not to the lowest degree, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list.
Source: https://edgeguides.rubyonrails.org/active_job_basics.html
0 Response to "Rails Resque Ioerror: Not Opened for Reading"
ارسال یک نظر