CINXE.COM
Active Job Basics — Ruby on Rails Guides
<!doctype html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Active Job Basics — Ruby on Rails Guides</title> <link rel="stylesheet" type="text/css" href="stylesheets/style-071e355820fc155a5c40ef8a1c0c4971.css" data-turbo-track="reload"> <link rel="stylesheet" type="text/css" href="stylesheets/print-a87ee66d50ce96bb83ac082f1249fe3e.css" media="print"> <link rel="stylesheet" type="text/css" href="stylesheets/highlight-a0d2133dd0073968b2d33b1f1360a2a3.css" data-turbo-track="reload"> <link rel="icon" href="images/favicon.ico" sizes="any"> <link rel="apple-touch-icon" href="images/icon.png"> <script src="javascripts/@hotwired--turbo-764f59c7edbeb902a9068c0340dd274e.js" data-turbo-track="reload"></script> <script src="javascripts/clipboard-8b7aed6f069f0cf58eeae353cd2f898b.js" data-turbo-track="reload"></script> <script src="javascripts/guides-897790ae3777ddd81bd4953f7ec99835.js" data-turbo-track="reload"></script> <meta property="og:title" content="Active Job Basics — Ruby on Rails Guides" /> <meta name="description" content="Active Job BasicsThis guide provides you with all you need to get started in creating, enqueuing and executing background jobs.After reading this guide, you will know: How to create jobs. How to enqueue jobs. How to run jobs in the background. How to send emails from your application asynchronously." /> <meta property="og:description" content="Active Job BasicsThis guide provides you with all you need to get started in creating, enqueuing and executing background jobs.After reading this guide, you will know: How to create jobs. How to enqueue jobs. How to run jobs in the background. How to send emails from your application asynchronously." /> <meta property="og:locale" content="en_US" /> <meta property="og:site_name" content="Ruby on Rails Guides" /> <meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <meta name="theme-color" content="#C81418"> </head> <body dir="ltr" class="guide no-js"> <script> document.body.classList.remove('no-js') </script> <a id="main-skip-link" href="#main" class="skip-link" data-turbo="false"> Skip to main content </a> <div id="mobile-navigation-bar"> <div class="wrapper"> <strong class="more-info-label">More at <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong> <button type="button" class="js-only red-button more-info-button" id="more-info" aria-controls="more-info-links" aria-expanded="false"> More Ruby on Rails </button> <ul id="more-info-links" class="more-info-links hidden"> <li class="more-info"><a href="https://rubyonrails.org/blog">Blog</a></li> <li class="more-info"><a href="https://guides.rubyonrails.org/">Guides</a></li> <li class="more-info"><a href="https://api.rubyonrails.org/">API</a></li> <li class="more-info"><a href="https://discuss.rubyonrails.org/">Forum</a></li> <li class="more-info"><a href="https://github.com/rails/rails">Contribute on GitHub</a></li> </ul> </div> </div> <header id="page-header"> <div class="wrapper clearfix"> <nav id="feature-nav"> <div class="header-logo"> <a href="index.html" title="Guides home for v8.0.0 Guides">Guides</a> <span id="version-switcher" class="js-only"> <label for="version-switcher-select">Version: <span class="visibly-hidden">pick from the list to go to that Rails version's guides</span></label> <select id="version-switcher-select" class="guides-version"> <option value="https://edgeguides.rubyonrails.org/">Edge</option> <option value="https://guides.rubyonrails.org/v8.0/" selected>8.0</option> <option value="https://guides.rubyonrails.org/v7.2/">7.2</option> <option value="https://guides.rubyonrails.org/v7.1/">7.1</option> <option value="https://guides.rubyonrails.org/v7.0/">7.0</option> <option value="https://guides.rubyonrails.org/v6.1/">6.1</option> <option value="https://guides.rubyonrails.org/v6.0/">6.0</option> <option value="https://guides.rubyonrails.org/v5.2/">5.2</option> <option value="https://guides.rubyonrails.org/v5.1/">5.1</option> <option value="https://guides.rubyonrails.org/v5.0/">5.0</option> <option value="https://guides.rubyonrails.org/v4.2/">4.2</option> <option value="https://guides.rubyonrails.org/v4.1/">4.1</option> <option value="https://guides.rubyonrails.org/v4.0/">4.0</option> <option value="https://guides.rubyonrails.org/v3.2/">3.2</option> <option value="https://guides.rubyonrails.org/v3.1/">3.1</option> <option value="https://guides.rubyonrails.org/v3.0/">3.0</option> <option value="https://guides.rubyonrails.org/v2.3/">2.3</option> </select> </span> </div> <ul class="nav"> <li><a class="nav-item" id="home_nav" href="https://rubyonrails.org/">Home</a></li> <li class="guides-index guides-index-large"> <a href="index.html" id="guides-menu-button" data-aria-controls="guides" data-aria-expanded="false" class="guides-index-item nav-item">Guides Index</a> <div id="guides" class="clearfix" style="display: none;"> <hr /> <dl class="guides-section-container"> <div class="guides-section"> <dt>Start Here</dt> <dd><a href="getting_started.html">Getting Started with Rails</a></dd> </div> <div class="guides-section"> <dt>Models</dt> <dd><a href="active_record_basics.html">Active Record Basics</a></dd> <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd> <dd><a href="active_record_validations.html">Active Record Validations</a></dd> <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd> <dd><a href="association_basics.html">Active Record Associations</a></dd> <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd> <dd><a href="active_model_basics.html">Active Model Basics</a></dd> </div> <div class="guides-section"> <dt>Views</dt> <dd><a href="action_view_overview.html">Action View Overview</a></dd> <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd> <dd><a href="action_view_helpers.html">Action View Helpers</a></dd> <dd><a href="form_helpers.html">Action View Form Helpers</a></dd> </div> <div class="guides-section"> <dt>Controllers</dt> <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd> <dd><a href="routing.html">Rails Routing from the Outside In</a></dd> </div> <div class="guides-section"> <dt>Other Components</dt> <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd> <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd> <dd><a href="action_mailbox_basics.html">Action Mailbox Basics</a></dd> <dd><a href="action_text_overview.html">Action Text Overview</a></dd> <dd><a href="active_job_basics.html">Active Job Basics</a></dd> <dd><a href="active_storage_overview.html">Active Storage Overview</a></dd> <dd><a href="action_cable_overview.html">Action Cable Overview</a></dd> </div> <div class="guides-section"> <dt>Digging Deeper</dt> <dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd> <dd><a href="testing.html">Testing Rails Applications</a></dd> <dd><a href="security.html">Securing Rails Applications</a></dd> <dd><a href="error_reporting.html">Error Reporting in Rails Applications</a></dd> <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd> <dd><a href="configuring.html">Configuring Rails Applications</a></dd> <dd><a href="command_line.html">The Rails Command Line</a></dd> <dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd> <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd> <dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading</a></dd> <dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd> <dd><a href="api_app.html">Using Rails for API-only Applications</a></dd> <dd><a href="tuning_performance_for_deployment.html">Tuning Performance for Deployment</a></dd> </div> <div class="guides-section"> <dt>Advanced Active Record</dt> <dd><a href="active_record_multiple_databases.html">Multiple Databases</a></dd> <dd><a href="active_record_composite_primary_keys.html">Composite Primary Keys</a></dd> </div> <div class="guides-section"> <dt>Extending Rails</dt> <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> <dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd> </div> <div class="guides-section"> <dt>Contributing</dt> <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd> <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd> <dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd> <dd><a href="development_dependencies_install.html">Installing Rails Core Development Dependencies</a></dd> </div> <div class="guides-section"> <dt>Policies</dt> <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd> </div> <div class="guides-section"> <dt>Release Notes</dt> <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd> <dd><a href="7_2_release_notes.html">Version 7.2 - August 2024</a></dd> <dd><a href="7_1_release_notes.html">Version 7.1 - October 2023</a></dd> <dd><a href="7_0_release_notes.html">Version 7.0 - December 2021</a></dd> <dd><a href="6_1_release_notes.html">Version 6.1 - December 2020</a></dd> <dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd> <dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd> <dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd> <dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd> <dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd> <dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd> <dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd> <dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd> <dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd> <dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd> <dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd> <dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd> </div> </dl> </div> </li> <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li> <li class="guides-index guides-index-small js-only"> <label for="guides-selector"> Navigate to a guide: </label> <select id="guides-selector" class="guides-index-item nav-item"> <option value="index.html">Guides Index</option> <optgroup label="Start Here"> <option value="getting_started.html">Getting Started with Rails</option> </optgroup> <optgroup label="Models"> <option value="active_record_basics.html">Active Record Basics</option> <option value="active_record_migrations.html">Active Record Migrations</option> <option value="active_record_validations.html">Active Record Validations</option> <option value="active_record_callbacks.html">Active Record Callbacks</option> <option value="association_basics.html">Active Record Associations</option> <option value="active_record_querying.html">Active Record Query Interface</option> <option value="active_model_basics.html">Active Model Basics</option> </optgroup> <optgroup label="Views"> <option value="action_view_overview.html">Action View Overview</option> <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option> <option value="action_view_helpers.html">Action View Helpers</option> <option value="form_helpers.html">Action View Form Helpers</option> </optgroup> <optgroup label="Controllers"> <option value="action_controller_overview.html">Action Controller Overview</option> <option value="routing.html">Rails Routing from the Outside In</option> </optgroup> <optgroup label="Other Components"> <option value="active_support_core_extensions.html">Active Support Core Extensions</option> <option value="action_mailer_basics.html">Action Mailer Basics</option> <option value="action_mailbox_basics.html">Action Mailbox Basics</option> <option value="action_text_overview.html">Action Text Overview</option> <option value="active_job_basics.html">Active Job Basics</option> <option value="active_storage_overview.html">Active Storage Overview</option> <option value="action_cable_overview.html">Action Cable Overview</option> </optgroup> <optgroup label="Digging Deeper"> <option value="i18n.html">Rails Internationalization (I18n) API</option> <option value="testing.html">Testing Rails Applications</option> <option value="security.html">Securing Rails Applications</option> <option value="error_reporting.html">Error Reporting in Rails Applications</option> <option value="debugging_rails_applications.html">Debugging Rails Applications</option> <option value="configuring.html">Configuring Rails Applications</option> <option value="command_line.html">The Rails Command Line</option> <option value="asset_pipeline.html">The Asset Pipeline</option> <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option> <option value="autoloading_and_reloading_constants.html">Autoloading and Reloading</option> <option value="caching_with_rails.html">Caching with Rails: An Overview</option> <option value="api_app.html">Using Rails for API-only Applications</option> <option value="tuning_performance_for_deployment.html">Tuning Performance for Deployment</option> </optgroup> <optgroup label="Advanced Active Record"> <option value="active_record_multiple_databases.html">Multiple Databases</option> <option value="active_record_composite_primary_keys.html">Composite Primary Keys</option> </optgroup> <optgroup label="Extending Rails"> <option value="rails_on_rack.html">Rails on Rack</option> <option value="generators.html">Creating and Customizing Rails Generators & Templates</option> </optgroup> <optgroup label="Contributing"> <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option> <option value="api_documentation_guidelines.html">API Documentation Guidelines</option> <option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option> <option value="development_dependencies_install.html">Installing Rails Core Development Dependencies</option> </optgroup> <optgroup label="Policies"> <option value="maintenance_policy.html">Maintenance Policy</option> </optgroup> <optgroup label="Release Notes"> <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option> <option value="7_2_release_notes.html">Version 7.2 - August 2024</option> <option value="7_1_release_notes.html">Version 7.1 - October 2023</option> <option value="7_0_release_notes.html">Version 7.0 - December 2021</option> <option value="6_1_release_notes.html">Version 6.1 - December 2020</option> <option value="6_0_release_notes.html">Version 6.0 - August 2019</option> <option value="5_2_release_notes.html">Version 5.2 - April 2018</option> <option value="5_1_release_notes.html">Version 5.1 - April 2017</option> <option value="5_0_release_notes.html">Version 5.0 - June 2016</option> <option value="4_2_release_notes.html">Version 4.2 - December 2014</option> <option value="4_1_release_notes.html">Version 4.1 - April 2014</option> <option value="4_0_release_notes.html">Version 4.0 - June 2013</option> <option value="3_2_release_notes.html">Version 3.2 - January 2012</option> <option value="3_1_release_notes.html">Version 3.1 - August 2011</option> <option value="3_0_release_notes.html">Version 3.0 - August 2010</option> <option value="2_3_release_notes.html">Version 2.3 - March 2009</option> <option value="2_2_release_notes.html">Version 2.2 - November 2008</option> </optgroup> </select> </li> </ul> </nav> </div> </header> <hr class="hide" /> <main id="main"> <article> <header id="feature"> <div class="wrapper"> <h1>Active Job Basics</h1><p>This guide provides you with all you need to get started in creating, enqueuing and executing background jobs.</p><p>After reading this guide, you will know:</p> <ul> <li>How to create jobs.</li> <li>How to enqueue jobs.</li> <li>How to run jobs in the background.</li> <li>How to send emails from your application asynchronously.</li> </ul> <nav id="column-side" aria-label="Chapter" class="guide-index" data-turbo="false"> <a id="chapter-nav-skip-link" href="#article-body" class="skip-link"> Skip to article body </a> <h2 class="chapter"> <picture aria-hidden="true"> <!-- Using the `source` HTML tag to set the dark theme image --> <source srcset="images/icon_book-close-bookmark-1-wht.svg" media="(prefers-color-scheme: dark)" /> <img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" /> </picture> Chapters </h2> <ol class="chapters"> <li><a href="#what-is-active-job-questionmark">What is Active Job?</a></li> <li><a href="#the-purpose-of-active-job">The Purpose of Active Job</a></li> <li><a href="#create-and-enqueue-jobs">Create and Enqueue Jobs</a> <ul> <li><a href="#create-the-job">Create the Job</a></li> <li><a href="#enqueue-the-job">Enqueue the Job</a></li> <li><a href="#enqueue-jobs-in-bulk">Enqueue Jobs in Bulk</a></li> </ul></li> <li><a href="#job-execution">Job Execution</a> <ul> <li><a href="#backends">Backends</a></li> <li><a href="#setting-the-backend">Setting the Backend</a></li> <li><a href="#starting-the-backend">Starting the Backend</a></li> </ul></li> <li><a href="#queues">Queues</a></li> <li><a href="#priority">Priority</a></li> <li><a href="#callbacks">Callbacks</a> <ul> <li><a href="#available-callbacks">Available Callbacks</a></li> </ul></li> <li><a href="#bulk-enqueuing">Bulk Enqueuing</a> <ul> <li><a href="#enqueue-multiple-active-job-classes">Enqueue Multiple Active Job Classes</a></li> <li><a href="#bulk-enqueue-callbacks">Bulk Enqueue Callbacks</a></li> <li><a href="#queue-backend-support">Queue Backend Support</a></li> </ul></li> <li><a href="#action-mailer">Action Mailer</a></li> <li><a href="#internationalization">Internationalization</a></li> <li><a href="#supported-types-for-arguments">Supported Types for Arguments</a> <ul> <li><a href="#globalid">GlobalID</a></li> <li><a href="#serializers">Serializers</a></li> </ul></li> <li><a href="#exceptions">Exceptions</a> <ul> <li><a href="#retrying-or-discarding-failed-jobs">Retrying or Discarding Failed Jobs</a></li> <li><a href="#deserialization">Deserialization</a></li> </ul></li> <li><a href="#job-testing">Job Testing</a></li> <li><a href="#debugging">Debugging</a></li> </ol> </nav> </div> </header> <div class="wrapper"> <div id="column-main"> <section id="article-body"> <h2 id="what-is-active-job-questionmark"><a class="anchorlink" href="#what-is-active-job-questionmark" data-turbo="false"><span>1</span> What is Active Job?</a></h2><p>Active Job is a framework for declaring jobs and making them run on a variety of queuing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel.</p><h2 id="the-purpose-of-active-job"><a class="anchorlink" href="#the-purpose-of-active-job" data-turbo="false"><span>2</span> The Purpose of Active Job</a></h2><p>The main point is to ensure that all Rails apps will have a job infrastructure 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.</p><div class="interstitial note"><p>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.</p></div><h2 id="create-and-enqueue-jobs"><a class="anchorlink" href="#create-and-enqueue-jobs" data-turbo="false"><span>3</span> Create and Enqueue Jobs</a></h2><p>This section will provide a step-by-step guide to creating a job and enqueuing it.</p><h3 id="create-the-job"><a class="anchorlink" href="#create-the-job" data-turbo="false"><span>3.1</span> Create the Job</a></h3><p>Active Job provides a Rails generator to create jobs. The following will create a job in <code>app/jobs</code> (with an attached test case under <code>test/jobs</code>):</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>generate job guests_cleanup <span class="go">invoke test_unit create test/jobs/guests_cleanup_job_test.rb create app/jobs/guests_cleanup_job.rb </span></code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails generate job guests_cleanup ">Copy</button> </div> <p>You can also create a job that will run on a specific queue:</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>generate job guests_cleanup <span class="nt">--queue</span> urgent </code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails generate job guests_cleanup --queue urgent ">Copy</button> </div> <p>If you don't want to use a generator, you could create your own file inside of <code>app/jobs</code>, just make sure that it inherits from <code>ApplicationJob</code>.</p><p>Here's what a job looks like:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:default</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="o">*</span><span class="n">guests</span><span class="p">)</span> <span class="c1"># Do something later</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :default def perform(*guests) # Do something later end end ">Copy</button> </div> <p>Note that you can define <code>perform</code> with as many arguments as you want.</p><p>If you already have an abstract class and its name differs from <code>ApplicationJob</code>, you can pass the <code>--parent</code> option to indicate you want a different abstract class:</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>generate job process_payment <span class="nt">--parent</span><span class="o">=</span>payment_job </code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails generate job process_payment --parent=payment_job ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProcessPaymentJob</span> <span class="o"><</span> <span class="no">PaymentJob</span> <span class="n">queue_as</span> <span class="ss">:default</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="c1"># Do something later</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProcessPaymentJob < PaymentJob queue_as :default def perform(*args) # Do something later end end ">Copy</button> </div> <h3 id="enqueue-the-job"><a class="anchorlink" href="#enqueue-the-job" data-turbo="false"><span>3.2</span> Enqueue the Job</a></h3><p>Enqueue a job using <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Enqueuing/ClassMethods.html#method-i-perform_later"><code>perform_later</code></a> and, optionally, <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Core/ClassMethods.html#method-i-set"><code>set</code></a>. Like so:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Enqueue a job to be performed as soon as the queuing system is</span> <span class="c1"># free.</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">perform_later</span> <span class="n">guest</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Enqueue a job to be performed as soon as the queuing system is # free. GuestsCleanupJob.perform_later guest ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Enqueue a job to be performed tomorrow at noon.</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">set</span><span class="p">(</span><span class="ss">wait_until: </span><span class="no">Date</span><span class="p">.</span><span class="nf">tomorrow</span><span class="p">.</span><span class="nf">noon</span><span class="p">).</span><span class="nf">perform_later</span><span class="p">(</span><span class="n">guest</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Enqueue a job to be performed tomorrow at noon. GuestsCleanupJob.set(wait_until: Date.tomorrow.noon).perform_later(guest) ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Enqueue a job to be performed 1 week from now.</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">set</span><span class="p">(</span><span class="ss">wait: </span><span class="mi">1</span><span class="p">.</span><span class="nf">week</span><span class="p">).</span><span class="nf">perform_later</span><span class="p">(</span><span class="n">guest</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Enqueue a job to be performed 1 week from now. GuestsCleanupJob.set(wait: 1.week).perform_later(guest) ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># `perform_now` and `perform_later` will call `perform` under the hood so</span> <span class="c1"># you can pass as many arguments as defined in the latter.</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">perform_later</span><span class="p">(</span><span class="n">guest1</span><span class="p">,</span> <span class="n">guest2</span><span class="p">,</span> <span class="ss">filter: </span><span class="s2">"some_filter"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# `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") ">Copy</button> </div> <p>That's it!</p><h3 id="enqueue-jobs-in-bulk"><a class="anchorlink" href="#enqueue-jobs-in-bulk" data-turbo="false"><span>3.3</span> Enqueue Jobs in Bulk</a></h3><p>You can enqueue multiple jobs at once using <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob.html#method-c-perform_all_later"><code>perform_all_later</code></a>. For more details see <a href="#bulk-enqueuing">Bulk Enqueuing</a>.</p><h2 id="job-execution"><a class="anchorlink" href="#job-execution" data-turbo="false"><span>4</span> Job Execution</a></h2><p>For enqueuing and executing jobs in production you need to set up a queuing backend, that is to say, you need to decide on 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 default async backend. This may be fine for smaller apps or non-critical jobs, but most production apps will need to pick a persistent backend.</p><h3 id="backends"><a class="anchorlink" href="#backends" data-turbo="false"><span>4.1</span> Backends</a></h3><p>Active Job 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 <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/QueueAdapters.html"><code>ActiveJob::QueueAdapters</code></a>.</p><h3 id="setting-the-backend"><a class="anchorlink" href="#setting-the-backend" data-turbo="false"><span>4.2</span> Setting the Backend</a></h3><p>You can easily set your queuing backend with <a href="configuring.html#config-active-job-queue-adapter"><code>config.active_job.queue_adapter</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="k">module</span> <span class="nn">YourApp</span> <span class="k">class</span> <span class="nc">Application</span> <span class="o"><</span> <span class="no">Rails</span><span class="o">::</span><span class="no">Application</span> <span class="c1"># Be sure to have the adapter's gem in your Gemfile</span> <span class="c1"># and follow the adapter's specific installation</span> <span class="c1"># and deployment instructions.</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_job</span><span class="p">.</span><span class="nf">queue_adapter</span> <span class="o">=</span> <span class="ss">:sidekiq</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module YourApp class Application < Rails::Application # Be sure to have the adapter's gem in your Gemfile # and follow the adapter's specific installation # and deployment instructions. config.active_job.queue_adapter = :sidekiq end end ">Copy</button> </div> <p>You can also configure your backend on a per job basis:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="nb">self</span><span class="p">.</span><span class="nf">queue_adapter</span> <span class="o">=</span> <span class="ss">:resque</span> <span class="c1"># ...</span> <span class="k">end</span> <span class="c1"># Now your job will use `resque` as its backend queue adapter, overriding what</span> <span class="c1"># was configured in `config.active_job.queue_adapter`.</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob self.queue_adapter = :resque # ... end # Now your job will use `resque` as its backend queue adapter, overriding what # was configured in `config.active_job.queue_adapter`. ">Copy</button> </div> <h3 id="starting-the-backend"><a class="anchorlink" href="#starting-the-backend" data-turbo="false"><span>4.3</span> Starting the Backend</a></h3><p>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 Rails app) for the job processing to work. Refer to library documentation for instructions on starting your queue backend.</p><p>Here is a noncomprehensive list of documentation:</p> <ul> <li><a href="https://github.com/mperham/sidekiq/wiki/Active-Job">Sidekiq</a></li> <li><a href="https://github.com/resque/resque/wiki/ActiveJob">Resque</a></li> <li><a href="https://github.com/jondot/sneakers/wiki/How-To:-Rails-Background-Jobs-with-ActiveJob">Sneakers</a></li> <li><a href="https://github.com/QueueClassic/queue_classic#active-job">Queue Classic</a></li> <li><a href="https://github.com/collectiveidea/delayed_job#active-job">Delayed Job</a></li> <li><a href="https://github.com/que-rb/que#additional-rails-specific-setup">Que</a></li> <li><a href="https://github.com/bensheldon/good_job#readme">Good Job</a></li> <li><a href="https://github.com/rails/solid_queue?tab=readme-ov-file#solid-queue">Solid Queue</a></li> </ul> <h2 id="queues"><a class="anchorlink" href="#queues" data-turbo="false"><span>5</span> Queues</a></h2><p>Most adapters support multiple queues. With Active Job you can schedule the job to run on a specific queue using <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/QueueName/ClassMethods.html#method-i-queue_as"><code>queue_as</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:low_priority</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :low_priority # ... end ">Copy</button> </div> <p>You can prefix the queue name for all your jobs using <a href="configuring.html#config-active-job-queue-name-prefix"><code>config.active_job.queue_name_prefix</code></a> in <code>application.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="k">module</span> <span class="nn">YourApp</span> <span class="k">class</span> <span class="nc">Application</span> <span class="o"><</span> <span class="no">Rails</span><span class="o">::</span><span class="no">Application</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_job</span><span class="p">.</span><span class="nf">queue_name_prefix</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">env</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module YourApp class Application < Rails::Application config.active_job.queue_name_prefix = Rails.env end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/jobs/guests_cleanup_job.rb</span> <span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:low_priority</span> <span class="c1"># ...</span> <span class="k">end</span> <span class="c1"># Now your job will run on queue production_low_priority on your</span> <span class="c1"># production environment and on staging_low_priority</span> <span class="c1"># on your staging environment</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :low_priority # ... end # Now your job will run on queue production_low_priority on your # production environment and on staging_low_priority # on your staging environment ">Copy</button> </div> <p>You can also configure the prefix on a per job basis.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:low_priority</span> <span class="nb">self</span><span class="p">.</span><span class="nf">queue_name_prefix</span> <span class="o">=</span> <span class="kp">nil</span> <span class="c1"># ...</span> <span class="k">end</span> <span class="c1"># Now your job's queue won't be prefixed, overriding what</span> <span class="c1"># was configured in `config.active_job.queue_name_prefix`.</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :low_priority self.queue_name_prefix = nil # ... end # Now your job's queue won't be prefixed, overriding what # was configured in `config.active_job.queue_name_prefix`. ">Copy</button> </div> <p>The default queue name prefix delimiter is '_'. This can be changed by setting <a href="configuring.html#config-active-job-queue-name-delimiter"><code>config.active_job.queue_name_delimiter</code></a> in <code>application.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="k">module</span> <span class="nn">YourApp</span> <span class="k">class</span> <span class="nc">Application</span> <span class="o"><</span> <span class="no">Rails</span><span class="o">::</span><span class="no">Application</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_job</span><span class="p">.</span><span class="nf">queue_name_prefix</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">env</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_job</span><span class="p">.</span><span class="nf">queue_name_delimiter</span> <span class="o">=</span> <span class="s2">"."</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module YourApp class Application < Rails::Application config.active_job.queue_name_prefix = Rails.env config.active_job.queue_name_delimiter = "." end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/jobs/guests_cleanup_job.rb</span> <span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:low_priority</span> <span class="c1"># ...</span> <span class="k">end</span> <span class="c1"># Now your job will run on queue production.low_priority on your</span> <span class="c1"># production environment and on staging.low_priority</span> <span class="c1"># on your staging environment</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :low_priority # ... end # Now your job will run on queue production.low_priority on your # production environment and on staging.low_priority # on your staging environment ">Copy</button> </div> <p>To control the queue from the job level you can pass a block to <code>queue_as</code>. The block will be executed in the job context (so it can access <code>self.arguments</code>), and it must return the queue name:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProcessVideoJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="k">do</span> <span class="n">video</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">arguments</span><span class="p">.</span><span class="nf">first</span> <span class="k">if</span> <span class="n">video</span><span class="p">.</span><span class="nf">owner</span><span class="p">.</span><span class="nf">premium?</span> <span class="ss">:premium_videojobs</span> <span class="k">else</span> <span class="ss">:videojobs</span> <span class="k">end</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="n">video</span><span class="p">)</span> <span class="c1"># Do process video</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProcessVideoJob < ApplicationJob queue_as do video = self.arguments.first if video.owner.premium? :premium_videojobs else :videojobs end end def perform(video) # Do process video end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ProcessVideoJob</span><span class="p">.</span><span class="nf">perform_later</span><span class="p">(</span><span class="no">Video</span><span class="p">.</span><span class="nf">last</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ProcessVideoJob.perform_later(Video.last) ">Copy</button> </div> <p>If you want more control on what queue a job will be run you can pass a <code>:queue</code> option to <code>set</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">MyJob</span><span class="p">.</span><span class="nf">set</span><span class="p">(</span><span class="ss">queue: :another_queue</span><span class="p">).</span><span class="nf">perform_later</span><span class="p">(</span><span class="n">record</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="MyJob.set(queue: :another_queue).perform_later(record) ">Copy</button> </div> <div class="interstitial note"><p>Make sure your queuing backend "listens" on your queue name. For some backends you need to specify the queues to listen to.</p></div><h2 id="priority"><a class="anchorlink" href="#priority" data-turbo="false"><span>6</span> Priority</a></h2><p>Some adapters support priorities at the job level, where jobs can be prioritized relative to others in the queue or across all queues.</p><p>You can schedule a job to run with a specific priority using <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/QueuePriority/ClassMethods.html#method-i-queue_with_priority"><code>queue_with_priority</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_with_priority</span> <span class="mi">10</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_with_priority 10 # ... end ">Copy</button> </div> <p>Note that this will not have any effect with adapters that do not support priorities.</p><p>Similar to <code>queue_as</code>, you can also pass a block to <code>queue_with_priority</code> to be evaluated in the job context:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProcessVideoJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_with_priority</span> <span class="k">do</span> <span class="n">video</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">arguments</span><span class="p">.</span><span class="nf">first</span> <span class="k">if</span> <span class="n">video</span><span class="p">.</span><span class="nf">owner</span><span class="p">.</span><span class="nf">premium?</span> <span class="mi">0</span> <span class="k">else</span> <span class="mi">10</span> <span class="k">end</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="n">video</span><span class="p">)</span> <span class="c1"># Process video</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProcessVideoJob < ApplicationJob queue_with_priority do video = self.arguments.first if video.owner.premium? 0 else 10 end end def perform(video) # Process video end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ProcessVideoJob</span><span class="p">.</span><span class="nf">perform_later</span><span class="p">(</span><span class="no">Video</span><span class="p">.</span><span class="nf">last</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ProcessVideoJob.perform_later(Video.last) ">Copy</button> </div> <p>You can also pass a <code>:priority</code> option to <code>set</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">MyJob</span><span class="p">.</span><span class="nf">set</span><span class="p">(</span><span class="ss">priority: </span><span class="mi">50</span><span class="p">).</span><span class="nf">perform_later</span><span class="p">(</span><span class="n">record</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="MyJob.set(priority: 50).perform_later(record) ">Copy</button> </div> <div class="interstitial note"><p>If a lower priority number performs before or after a higher priority number depends on the adapter implementation. Refer to documentation of your backend for more information. Adapter authors are encouraged to treat a lower number as more important.</p></div><h2 id="callbacks"><a class="anchorlink" href="#callbacks" data-turbo="false"><span>7</span> Callbacks</a></h2><p>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:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:default</span> <span class="n">around_perform</span> <span class="ss">:around_cleanup</span> <span class="k">def</span> <span class="nf">perform</span> <span class="c1"># Do something later</span> <span class="k">end</span> <span class="kp">private</span> <span class="k">def</span> <span class="nf">around_cleanup</span> <span class="c1"># Do something before perform</span> <span class="k">yield</span> <span class="c1"># Do something after perform</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :default around_perform :around_cleanup def perform # Do something later end private def around_cleanup # Do something before perform yield # Do something after perform end end ">Copy</button> </div> <p>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:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ApplicationJob</span> <span class="o"><</span> <span class="no">ActiveJob</span><span class="o">::</span><span class="no">Base</span> <span class="n">before_enqueue</span> <span class="p">{</span> <span class="o">|</span><span class="n">job</span><span class="o">|</span> <span class="vg">$statsd</span><span class="p">.</span><span class="nf">increment</span> <span class="s2">"</span><span class="si">#{</span><span class="n">job</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">underscore</span><span class="si">}</span><span class="s2">.enqueue"</span> <span class="p">}</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationJob < ActiveJob::Base before_enqueue { |job| $statsd.increment "#{job.class.name.underscore}.enqueue" } end ">Copy</button> </div> <h3 id="available-callbacks"><a class="anchorlink" href="#available-callbacks" data-turbo="false"><span>7.1</span> Available Callbacks</a></h3> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-before_enqueue"><code>before_enqueue</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-around_enqueue"><code>around_enqueue</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-after_enqueue"><code>after_enqueue</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-before_perform"><code>before_perform</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-around_perform"><code>around_perform</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-after_perform"><code>after_perform</code></a></li> </ul> <p>Please note that when enqueuing jobs in bulk using <code>perform_all_later</code>, callbacks such as <code>around_enqueue</code> will not be triggered on the individual jobs. See <a href="#bulk-enqueue-callbacks">Bulk Enqueuing Callbacks</a>.</p><h2 id="bulk-enqueuing"><a class="anchorlink" href="#bulk-enqueuing" data-turbo="false"><span>8</span> Bulk Enqueuing</a></h2><p>You can enqueue multiple jobs at once using <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob.html#method-c-perform_all_later"><code>perform_all_later</code></a>. Bulk enqueuing reduces the number of round trips to the queue data store (like Redis or a database), making it a more performant operation than enqueuing the same jobs individually.</p><p><code>perform_all_later</code> is a top-level API on Active Job. It accepts instantiated jobs as arguments (note that this is different from <code>perform_later</code>). <code>perform_all_later</code> does call <code>perform</code> under the hood. The arguments passed to <code>new</code> will be passed on to <code>perform</code> when it's eventually called.</p><p>Here is an example calling <code>perform_all_later</code> with <code>GuestCleanupJob</code> instances:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Create jobs to pass to `perform_all_later`.</span> <span class="c1"># The arguments to `new` are passed on to `perform`</span> <span class="n">guest_cleanup_jobs</span> <span class="o">=</span> <span class="no">Guest</span><span class="p">.</span><span class="nf">all</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">guest</span><span class="o">|</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">guest</span><span class="p">)</span> <span class="p">}</span> <span class="c1"># Will enqueue a separate job for each instance of `GuestCleanupJob`</span> <span class="no">ActiveJob</span><span class="p">.</span><span class="nf">perform_all_later</span><span class="p">(</span><span class="n">guest_cleanup_jobs</span><span class="p">)</span> <span class="c1"># Can also use `set` method to configure options before bulk enqueuing jobs.</span> <span class="n">guest_cleanup_jobs</span> <span class="o">=</span> <span class="no">Guest</span><span class="p">.</span><span class="nf">all</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">guest</span><span class="o">|</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">guest</span><span class="p">).</span><span class="nf">set</span><span class="p">(</span><span class="ss">wait: </span><span class="mi">1</span><span class="p">.</span><span class="nf">day</span><span class="p">)</span> <span class="p">}</span> <span class="no">ActiveJob</span><span class="p">.</span><span class="nf">perform_all_later</span><span class="p">(</span><span class="n">guest_cleanup_jobs</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Create jobs to pass to `perform_all_later`. # The arguments to `new` are passed on to `perform` guest_cleanup_jobs = Guest.all.map { |guest| GuestsCleanupJob.new(guest) } # Will enqueue a separate job for each instance of `GuestCleanupJob` ActiveJob.perform_all_later(guest_cleanup_jobs) # Can also use `set` method to configure options before bulk enqueuing jobs. guest_cleanup_jobs = Guest.all.map { |guest| GuestsCleanupJob.new(guest).set(wait: 1.day) } ActiveJob.perform_all_later(guest_cleanup_jobs) ">Copy</button> </div> <p><code>perform_all_later</code> logs the number of jobs successfully enqueued, for example if <code>Guest.all.map</code> above resulted in 3 <code>guest_cleanup_jobs</code>, it would log <code>Enqueued 3 jobs to Async (3 GuestsCleanupJob)</code> (assuming all were enqueued).</p><p>The return value of <code>perform_all_later</code> is <code>nil</code>. Note that this is different from <code>perform_later</code>, which returns the instance of the queued job class.</p><h3 id="enqueue-multiple-active-job-classes"><a class="anchorlink" href="#enqueue-multiple-active-job-classes" data-turbo="false"><span>8.1</span> Enqueue Multiple Active Job Classes</a></h3><p>With <code>perform_all_later</code>, it's also possible to enqueue different Active Job class instances in the same call. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ExportDataJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="c1"># Export data</span> <span class="k">end</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">NotifyGuestsJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="o">*</span><span class="n">guests</span><span class="p">)</span> <span class="c1"># Email guests</span> <span class="k">end</span> <span class="k">end</span> <span class="c1"># Instantiate job instances</span> <span class="n">cleanup_job</span> <span class="o">=</span> <span class="no">GuestsCleanupJob</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">guest</span><span class="p">)</span> <span class="n">export_job</span> <span class="o">=</span> <span class="no">ExportDataJob</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="n">notify_job</span> <span class="o">=</span> <span class="no">NotifyGuestsJob</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">guest</span><span class="p">)</span> <span class="c1"># Enqueues job instances from multiple classes at once</span> <span class="no">ActiveJob</span><span class="p">.</span><span class="nf">perform_all_later</span><span class="p">(</span><span class="n">cleanup_job</span><span class="p">,</span> <span class="n">export_job</span><span class="p">,</span> <span class="n">notify_job</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ExportDataJob < ApplicationJob def perform(*args) # Export data end end class NotifyGuestsJob < ApplicationJob def perform(*guests) # Email guests end end # Instantiate job instances cleanup_job = GuestsCleanupJob.new(guest) export_job = ExportDataJob.new(data) notify_job = NotifyGuestsJob.new(guest) # Enqueues job instances from multiple classes at once ActiveJob.perform_all_later(cleanup_job, export_job, notify_job) ">Copy</button> </div> <h3 id="bulk-enqueue-callbacks"><a class="anchorlink" href="#bulk-enqueue-callbacks" data-turbo="false"><span>8.2</span> Bulk Enqueue Callbacks</a></h3><p>When enqueuing jobs in bulk using <code>perform_all_later</code>, callbacks such as <code>around_enqueue</code> will not be triggered on the individual jobs. This behavior is in line with other Active Record bulk methods. Since callbacks run on individual jobs, they can't take advantage of the bulk nature of this method.</p><p>However, the <code>perform_all_later</code> method does fire an <a href="active_support_instrumentation.html#enqueue-all-active-job"><code>enqueue_all.active_job</code></a> event which you can subscribe to using <code>ActiveSupport::Notifications</code>.</p><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Core.html#method-i-successfully_enqueued-3F"><code>successfully_enqueued?</code></a> can be used to find out if a given job was successfully enqueued.</p><h3 id="queue-backend-support"><a class="anchorlink" href="#queue-backend-support" data-turbo="false"><span>8.3</span> Queue Backend Support</a></h3><p>For <code>perform_all_later</code>, bulk enqueuing needs to be backed by the <a href="#backends">queue backend</a>.</p><p>For example, Sidekiq has a <code>push_bulk</code> method, which can push a large number of jobs to Redis and prevent the round trip network latency. GoodJob also supports bulk enqueuing with the <code>GoodJob::Bulk.enqueue</code> method. The new queue backend <a href="https://github.com/rails/solid_queue/pull/93"><code>Solid Queue</code></a> has added support for bulk enqueuing as well.</p><p>If the queue backend does <em>not</em> support bulk enqueuing, <code>perform_all_later</code> will enqueue jobs one by one.</p><h2 id="action-mailer"><a class="anchorlink" href="#action-mailer" data-turbo="false"><span>9</span> Action Mailer</a></h2><p>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 is integrated with Action Mailer so you can easily send emails asynchronously:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># If you want to send the email now use #deliver_now</span> <span class="no">UserMailer</span><span class="p">.</span><span class="nf">welcome</span><span class="p">(</span><span class="vi">@user</span><span class="p">).</span><span class="nf">deliver_now</span> <span class="c1"># If you want to send the email through Active Job use #deliver_later</span> <span class="no">UserMailer</span><span class="p">.</span><span class="nf">welcome</span><span class="p">(</span><span class="vi">@user</span><span class="p">).</span><span class="nf">deliver_later</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# If you want to send the email now use #deliver_now UserMailer.welcome(@user).deliver_now # If you want to send the email through Active Job use #deliver_later UserMailer.welcome(@user).deliver_later ">Copy</button> </div> <div class="interstitial note"><p>Using the asynchronous queue from a Rake task (for example, to send an email using <code>.deliver_later</code>) will generally not work because Rake will likely end, causing the in-process thread pool to be deleted, before any/all of the <code>.deliver_later</code> emails are processed. To avoid this problem, use <code>.deliver_now</code> or run a persistent queue in development.</p></div><h2 id="internationalization"><a class="anchorlink" href="#internationalization" data-turbo="false"><span>10</span> Internationalization</a></h2><p>Each job uses the <code>I18n.locale</code> set when the job was created. This is useful if you send emails asynchronously:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">locale</span> <span class="o">=</span> <span class="ss">:eo</span> <span class="no">UserMailer</span><span class="p">.</span><span class="nf">welcome</span><span class="p">(</span><span class="vi">@user</span><span class="p">).</span><span class="nf">deliver_later</span> <span class="c1"># Email will be localized to Esperanto.</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.locale = :eo UserMailer.welcome(@user).deliver_later # Email will be localized to Esperanto. ">Copy</button> </div> <h2 id="supported-types-for-arguments"><a class="anchorlink" href="#supported-types-for-arguments" data-turbo="false"><span>11</span> Supported Types for Arguments</a></h2><p>ActiveJob supports the following types of arguments by default:</p> <ul> <li>Basic types (<code>NilClass</code>, <code>String</code>, <code>Integer</code>, <code>Float</code>, <code>BigDecimal</code>, <code>TrueClass</code>, <code>FalseClass</code>)</li> <li><code>Symbol</code></li> <li><code>Date</code></li> <li><code>Time</code></li> <li><code>DateTime</code></li> <li><code>ActiveSupport::TimeWithZone</code></li> <li><code>ActiveSupport::Duration</code></li> <li><code>Hash</code> (Keys should be of <code>String</code> or <code>Symbol</code> type)</li> <li><code>ActiveSupport::HashWithIndifferentAccess</code></li> <li><code>Array</code></li> <li><code>Range</code></li> <li><code>Module</code></li> <li><code>Class</code></li> </ul> <h3 id="globalid"><a class="anchorlink" href="#globalid" data-turbo="false"><span>11.1</span> GlobalID</a></h3><p>Active Job supports <a href="https://github.com/rails/globalid/blob/main/README.md">GlobalID</a> 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:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">TrashableCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="n">trashable_class</span><span class="p">,</span> <span class="n">trashable_id</span><span class="p">,</span> <span class="n">depth</span><span class="p">)</span> <span class="n">trashable</span> <span class="o">=</span> <span class="n">trashable_class</span><span class="p">.</span><span class="nf">constantize</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">trashable_id</span><span class="p">)</span> <span class="n">trashable</span><span class="p">.</span><span class="nf">cleanup</span><span class="p">(</span><span class="n">depth</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class TrashableCleanupJob < ApplicationJob def perform(trashable_class, trashable_id, depth) trashable = trashable_class.constantize.find(trashable_id) trashable.cleanup(depth) end end ">Copy</button> </div> <p>Now you can simply do:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">TrashableCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="n">trashable</span><span class="p">,</span> <span class="n">depth</span><span class="p">)</span> <span class="n">trashable</span><span class="p">.</span><span class="nf">cleanup</span><span class="p">(</span><span class="n">depth</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class TrashableCleanupJob < ApplicationJob def perform(trashable, depth) trashable.cleanup(depth) end end ">Copy</button> </div> <p>This works with any class that mixes in <code>GlobalID::Identification</code>, which by default has been mixed into Active Record classes.</p><h3 id="serializers"><a class="anchorlink" href="#serializers" data-turbo="false"><span>11.2</span> Serializers</a></h3><p>You can extend the list of supported argument types. You just need to define your own serializer:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/serializers/money_serializer.rb</span> <span class="k">class</span> <span class="nc">MoneySerializer</span> <span class="o"><</span> <span class="no">ActiveJob</span><span class="o">::</span><span class="no">Serializers</span><span class="o">::</span><span class="no">ObjectSerializer</span> <span class="c1"># Converts an object to a simpler representative using supported object types.</span> <span class="c1"># The recommended representative is a Hash with a specific key. Keys can be of basic types only.</span> <span class="c1"># You should call `super` to add the custom serializer type to the hash.</span> <span class="k">def</span> <span class="nf">serialize</span><span class="p">(</span><span class="n">money</span><span class="p">)</span> <span class="k">super</span><span class="p">(</span> <span class="s2">"amount"</span> <span class="o">=></span> <span class="n">money</span><span class="p">.</span><span class="nf">amount</span><span class="p">,</span> <span class="s2">"currency"</span> <span class="o">=></span> <span class="n">money</span><span class="p">.</span><span class="nf">currency</span> <span class="p">)</span> <span class="k">end</span> <span class="c1"># Converts serialized value into a proper object.</span> <span class="k">def</span> <span class="nf">deserialize</span><span class="p">(</span><span class="nb">hash</span><span class="p">)</span> <span class="no">Money</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="nb">hash</span><span class="p">[</span><span class="s2">"amount"</span><span class="p">],</span> <span class="nb">hash</span><span class="p">[</span><span class="s2">"currency"</span><span class="p">])</span> <span class="k">end</span> <span class="kp">private</span> <span class="c1"># Checks if an argument should be serialized by this serializer.</span> <span class="k">def</span> <span class="nf">klass</span> <span class="no">Money</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class MoneySerializer < ActiveJob::Serializers::ObjectSerializer # Converts an object to a simpler representative using supported object types. # The recommended representative is a Hash with a specific key. Keys can be of basic types only. # You should call `super` to add the custom serializer type to the hash. def serialize(money) super( "amount" => money.amount, "currency" => money.currency ) end # Converts serialized value into a proper object. def deserialize(hash) Money.new(hash["amount"], hash["currency"]) end private # Checks if an argument should be serialized by this serializer. def klass Money end end ">Copy</button> </div> <p>and add this serializer to the list:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/initializers/custom_serializers.rb</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">active_job</span><span class="p">.</span><span class="nf">custom_serializers</span> <span class="o"><<</span> <span class="no">MoneySerializer</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.config.active_job.custom_serializers << MoneySerializer ">Copy</button> </div> <p>Note that autoloading reloadable code during initialization is not supported. Thus it is recommended to set-up serializers to be loaded only once, e.g. by amending <code>config/application.rb</code> like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="k">module</span> <span class="nn">YourApp</span> <span class="k">class</span> <span class="nc">Application</span> <span class="o"><</span> <span class="no">Rails</span><span class="o">::</span><span class="no">Application</span> <span class="n">config</span><span class="p">.</span><span class="nf">autoload_once_paths</span> <span class="o"><<</span> <span class="s2">"</span><span class="si">#{</span><span class="n">root</span><span class="si">}</span><span class="s2">/app/serializers"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module YourApp class Application < Rails::Application config.autoload_once_paths << "#{root}/app/serializers" end end ">Copy</button> </div> <h2 id="exceptions"><a class="anchorlink" href="#exceptions" data-turbo="false"><span>12</span> Exceptions</a></h2><p>Exceptions raised during the execution of the job can be handled with <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from"><code>rescue_from</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">GuestsCleanupJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">queue_as</span> <span class="ss">:default</span> <span class="n">rescue_from</span><span class="p">(</span><span class="no">ActiveRecord</span><span class="o">::</span><span class="no">RecordNotFound</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">exception</span><span class="o">|</span> <span class="c1"># Do something with the exception</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">perform</span> <span class="c1"># Do something later</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class GuestsCleanupJob < ApplicationJob queue_as :default rescue_from(ActiveRecord::RecordNotFound) do |exception| # Do something with the exception end def perform # Do something later end end ">Copy</button> </div> <p>If an exception from a job is not rescued, then the job is referred to as "failed".</p><h3 id="retrying-or-discarding-failed-jobs"><a class="anchorlink" href="#retrying-or-discarding-failed-jobs" data-turbo="false"><span>12.1</span> Retrying or Discarding Failed Jobs</a></h3><p>A failed job will not be retried, unless configured otherwise.</p><p>It's possible to retry or discard a failed job by using <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Exceptions/ClassMethods.html#method-i-retry_on"><code>retry_on</code></a> or <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/Exceptions/ClassMethods.html#method-i-discard_on"><code>discard_on</code></a>, respectively. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">RemoteServiceJob</span> <span class="o"><</span> <span class="no">ApplicationJob</span> <span class="n">retry_on</span> <span class="no">CustomAppException</span> <span class="c1"># defaults to 3s wait, 5 attempts</span> <span class="n">discard_on</span> <span class="no">ActiveJob</span><span class="o">::</span><span class="no">DeserializationError</span> <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="c1"># Might raise CustomAppException or ActiveJob::DeserializationError</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class RemoteServiceJob < ApplicationJob retry_on CustomAppException # defaults to 3s wait, 5 attempts discard_on ActiveJob::DeserializationError def perform(*args) # Might raise CustomAppException or ActiveJob::DeserializationError end end ">Copy</button> </div> <h3 id="deserialization"><a class="anchorlink" href="#deserialization" data-turbo="false"><span>12.2</span> Deserialization</a></h3><p>GlobalID allows serializing full Active Record objects passed to <code>#perform</code>.</p><p>If a passed record is deleted after the job is enqueued but before the <code>#perform</code> method is called Active Job will raise an <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveJob/DeserializationError.html"><code>ActiveJob::DeserializationError</code></a> exception.</p><h2 id="job-testing"><a class="anchorlink" href="#job-testing" data-turbo="false"><span>13</span> Job Testing</a></h2><p>You can find detailed instructions on how to test your jobs in the <a href="testing.html#testing-jobs">testing guide</a>.</p><h2 id="debugging"><a class="anchorlink" href="#debugging" data-turbo="false"><span>14</span> Debugging</a></h2><p>If you need help figuring out where jobs are coming from, you can enable <a href="debugging_rails_applications.html#verbose-enqueue-logs">verbose logging</a>.</p> </section> <hr> <footer aria-labelledby="heading-feedback" role="region"> <h2 id="heading-feedback">Feedback</h2> <p> You're encouraged to help improve the quality of this guide. </p> <p> Please contribute if you see any typos or factual errors. To get started, you can read our <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section. </p> <p> You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check <a href="https://edgeguides.rubyonrails.org">Edge Guides</a> first to verify if the issues are already fixed or not on the main branch. Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a> for style and conventions. </p> <p> If for whatever reason you spot something to fix but cannot patch it yourself, please <a href="https://github.com/rails/rails/issues">open an issue</a>. </p> <p>And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the <a href="https://discuss.rubyonrails.org/c/rubyonrails-docs">official Ruby on Rails Forum</a>. </p> </footer> </div> </article> </main> <hr class="hide" /> <footer id="complementary"> <div class="wrapper"> <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p> <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> </div> </footer> <a href="#main-skip-link" class="back-to-top" data-turbo="false"><span class="visibly-hidden">Back to top</span></a> </body> </html>