{"id":13400439,"url":"https://github.com/collectiveidea/delayed_job","last_synced_at":"2025-10-05T20:30:45.505Z","repository":{"id":431756,"uuid":"52287","full_name":"collectiveidea/delayed_job","owner":"collectiveidea","description":"Database based asynchronous priority queue system -- Extracted from Shopify ","archived":false,"fork":true,"pushed_at":"2024-12-27T16:43:47.000Z","size":1475,"stargazers_count":4816,"open_issues_count":138,"forks_count":953,"subscribers_count":74,"default_branch":"master","last_synced_at":"2025-01-22T07:36:45.850Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://groups.google.com/group/delayed_job","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"tobi/delayed_job","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/collectiveidea.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2008-09-13T14:27:37.000Z","updated_at":"2025-01-22T05:37:25.000Z","dependencies_parsed_at":"2023-10-02T18:38:38.476Z","dependency_job_id":null,"html_url":"https://github.com/collectiveidea/delayed_job","commit_stats":{"total_commits":880,"total_committers":186,"mean_commits":4.731182795698925,"dds":0.7738636363636364,"last_synced_commit":"92fb435131d05b8a8715ac52acaacd9cde89619c"},"previous_names":[],"tags_count":63,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/collectiveidea%2Fdelayed_job","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/collectiveidea%2Fdelayed_job/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/collectiveidea%2Fdelayed_job/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/collectiveidea%2Fdelayed_job/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/collectiveidea","download_url":"https://codeload.github.com/collectiveidea/delayed_job/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235246418,"owners_count":18959225,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T19:00:52.047Z","updated_at":"2025-10-05T20:30:40.471Z","avatar_url":"https://github.com/collectiveidea.png","language":"Ruby","funding_links":[],"categories":["Ruby","Scheduled/Recurrence Jobs","Background Processing","定时任务","Queues and Messaging","Queue","Background Jobs \u0026 Queues"],"sub_categories":["Omniauth","Background Jobs"],"readme":"**If you're viewing this at https://github.com/collectiveidea/delayed_job,\nyou're reading the documentation for the master branch.\n[View documentation for the latest release\n(4.1.13).](https://github.com/collectiveidea/delayed_job/tree/v4.1.13)**\n\nDelayed::Job\n============\n[![Gem Version](https://badge.fury.io/rb/delayed_job.svg)][gem]\n![CI](https://github.com/collectiveidea/delayed_job/workflows/CI/badge.svg)\n[![Code Climate](https://codeclimate.com/github/collectiveidea/delayed_job.svg)][codeclimate]\n[![Coverage Status](https://coveralls.io/repos/collectiveidea/delayed_job/badge.svg?branch=master)][coveralls]\n\n[gem]: https://rubygems.org/gems/delayed_job\n[codeclimate]: https://codeclimate.com/github/collectiveidea/delayed_job\n[coveralls]: https://coveralls.io/r/collectiveidea/delayed_job\n\nDelayed::Job (or DJ) encapsulates the common pattern of asynchronously executing\nlonger tasks in the background.\n\nIt is a direct extraction from Shopify where the job table is responsible for a\nmultitude of core tasks. Amongst those tasks are:\n\n* sending massive newsletters\n* image resizing\n* http downloads\n* updating smart collections\n* updating solr, our search server, after product changes\n* batch imports\n* spam checks\n\n[Follow us on Twitter][twitter] to get updates and notices about new releases.\n\n[twitter]: https://twitter.com/delayedjob\n\nInstallation\n============\ndelayed_job 3.0.0 only supports Rails 3.0+.\n\ndelayed_job supports multiple backends for storing the job queue. [See the wiki\nfor other backends](https://github.com/collectiveidea/delayed_job/wiki/Backends).\n\nIf you plan to use delayed_job with Active Record, add `delayed_job_active_record` to your `Gemfile`.\n\n```ruby\ngem 'delayed_job_active_record'\n```\n\nIf you plan to use delayed_job with Mongoid, add `delayed_job_mongoid` to your `Gemfile`.\n\n```ruby\ngem 'delayed_job_mongoid'\n```\n\nRun `bundle install` to install the backend and delayed_job gems.\n\nThe Active Record backend requires a jobs table. You can create that table by\nrunning the following command:\n\n    rails generate delayed_job:active_record\n    rake db:migrate\n\nFor Rails 4.2+, see [below](#active-job)\n\nDevelopment\n===========\nIn development mode, if you are using Rails 3.1+, your application code will automatically reload every 100 jobs or when the queue finishes.\nYou no longer need to restart Delayed Job every time you update your code in development.\n\nActive Job\n==========\nIn Rails 4.2+, set the queue_adapter in config/application.rb\n\n```ruby\nconfig.active_job.queue_adapter = :delayed_job\n```\n\nSee the [rails guide](http://guides.rubyonrails.org/active_job_basics.html#setting-the-backend) for more details.\n\nRails 4.x\n=========\nIf you are using the protected_attributes gem, it must appear before delayed_job in your gemfile. If your jobs are failing with:\n\n     ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column \"handler\" violates not-null constraint\n\nthen this is the fix you're looking for.\n\nUpgrading from 2.x to 3.0.0 on Active Record\n============================================\nDelayed Job 3.0.0 introduces a new column to the delayed_jobs table.\n\nIf you're upgrading from Delayed Job 2.x, run the upgrade generator to create a migration to add the column.\n\n    rails generate delayed_job:upgrade\n    rake db:migrate\n\nQueuing Jobs\n============\nCall `.delay.method(params)` on any object and it will be processed in the background.\n\n```ruby\n# without delayed_job\n@user.activate!(@device)\n\n# with delayed_job\n@user.delay.activate!(@device)\n```\n\nIf a method should always be run in the background, you can call\n`#handle_asynchronously` after the method declaration:\n\n```ruby\nclass Device\n  def deliver\n    # long running method\n  end\n  handle_asynchronously :deliver\nend\n\ndevice = Device.new\ndevice.deliver\n```\n\n## Parameters\n\n`#handle_asynchronously` and `#delay` take these parameters:\n\n- `:priority` (number): lower numbers run first; default is 0 but can be reconfigured (see below)\n- `:run_at` (Time): run the job after this time (probably in the future)\n- `:queue` (string): named queue to put this job in, an alternative to priorities (see below)\n\nThese params can be Proc objects, allowing call-time evaluation of the value.\n\nFor example:\n\n```ruby\nclass LongTasks\n  def send_mailer\n    # Some other code\n  end\n  handle_asynchronously :send_mailer, :priority =\u003e 20\n\n  def in_the_future\n    # Some other code\n  end\n  # 5.minutes.from_now will be evaluated when in_the_future is called\n  handle_asynchronously :in_the_future, :run_at =\u003e Proc.new { 5.minutes.from_now }\n\n  def self.when_to_run\n    2.hours.from_now\n  end\n\n  class \u003c\u003c self\n    def call_a_class_method\n      # Some other code\n    end\n    handle_asynchronously :call_a_class_method, :run_at =\u003e Proc.new { when_to_run }\n  end\n\n  attr_reader :how_important\n\n  def call_an_instance_method\n    # Some other code\n  end\n  handle_asynchronously :call_an_instance_method, :priority =\u003e Proc.new {|i| i.how_important }\nend\n```\n\nIf you ever want to call a `handle_asynchronously`'d method without Delayed Job, for instance while debugging something at the console, just add `_without_delay` to the method name. For instance, if your original method was `foo`, then call `foo_without_delay`.\n\nRails Mailers\n=============\nDelayed Job uses special syntax for Rails Mailers.\nDo not call the `.deliver` method when using `.delay`.\n\n```ruby\n# without delayed_job\nNotifier.signup(@user).deliver\n\n# with delayed_job\nNotifier.delay.signup(@user)\n\n# delayed_job running at a specific time\nNotifier.delay(run_at: 5.minutes.from_now).signup(@user)\n\n# when using parameters, the .with method must be called before the .delay method\nNotifier.with(foo: 1, bar: 2).delay.signup(@user)\n```\n\nYou may also wish to consider using\n[Active Job with Action Mailer](https://edgeguides.rubyonrails.org/active_job_basics.html#action-mailer)\nwhich provides convenient `.deliver_later` syntax that forwards to Delayed Job under-the-hood.\n\nNamed Queues\n============\nDJ 3 introduces Resque-style named queues while still retaining DJ-style\npriority. The goal is to provide a system for grouping tasks to be worked by\nseparate pools of workers, which may be scaled and controlled individually.\n\nJobs can be assigned to a queue by setting the `queue` option:\n\n```ruby\nobject.delay(:queue =\u003e 'tracking').method\n\nDelayed::Job.enqueue job, :queue =\u003e 'tracking'\n\nhandle_asynchronously :tweet_later, :queue =\u003e 'tweets'\n```\n\nYou can configure default priorities for named queues:\n\n```ruby\nDelayed::Worker.queue_attributes = {\n  high_priority: { priority: -10 },\n  low_priority: { priority: 10 }\n}\n```\n\nConfigured queue priorities can be overriden by passing priority to the delay method\n\n```ruby\nobject.delay(:queue =\u003e 'high_priority', priority: 0).method\n```\n\nYou can start processes to only work certain queues with the `queue` and `queues`\noptions defined below. Processes started without specifying a queue will run jobs\nfrom **any** queue. To effectively have a process that runs jobs where a queue is not\nspecified, set a default queue name with `Delayed::Worker.default_queue_name` and\nhave the processes run that queue.\n\nRunning Jobs\n============\n`script/delayed_job` can be used to manage a background process which will\nstart working off jobs.\n\nTo do so, add `gem \"daemons\"` to your `Gemfile` and make sure you've run `rails\ngenerate delayed_job`.\n\nYou can then do the following:\n\n    RAILS_ENV=production script/delayed_job start\n    RAILS_ENV=production script/delayed_job stop\n\n    # Runs two workers in separate processes.\n    RAILS_ENV=production script/delayed_job -n 2 start\n    RAILS_ENV=production script/delayed_job stop\n\n    # Set the --queue or --queues option to work from a particular queue.\n    RAILS_ENV=production script/delayed_job --queue=tracking start\n    RAILS_ENV=production script/delayed_job --queues=mailers,tasks start\n\n    # Use the --pool option to specify a worker pool. You can use this option multiple times to start different numbers of workers for different queues.\n    # The following command will start 1 worker for the tracking queue,\n    # 2 workers for the mailers and tasks queues, and 2 workers for any jobs:\n    RAILS_ENV=production script/delayed_job --pool=tracking --pool=mailers,tasks:2 --pool=*:2 start\n\n    # Runs all available jobs and then exits\n    RAILS_ENV=production script/delayed_job start --exit-on-complete\n    # or to run in the foreground\n    RAILS_ENV=production script/delayed_job run --exit-on-complete\n\n**Rails 4:** *replace script/delayed_job with bin/delayed_job*\n\nWorkers can be running on any computer, as long as they have access to the\ndatabase and their clock is in sync. Keep in mind that each worker will check\nthe database at least every 5 seconds.\n\nYou can also invoke `rake jobs:work` which will start working off jobs. You can\ncancel the rake task with `CTRL-C`.\n\nIf you want to just run all available jobs and exit you can use `rake jobs:workoff`\n\nWork off queues by setting the `QUEUE` or `QUEUES` environment variable.\n\n    QUEUE=tracking rake jobs:work\n    QUEUES=mailers,tasks rake jobs:work\n\nRestarting delayed_job\n======================\n\nThe following syntax will restart delayed jobs:\n\n    RAILS_ENV=production script/delayed_job restart\n\nTo restart multiple delayed_job workers:\n\n    RAILS_ENV=production script/delayed_job -n2 restart\n\n**Rails 4:** *replace script/delayed_job with bin/delayed_job*\n\n\n\nCustom Jobs\n===========\nJobs are simple ruby objects with a method called perform. Any object which responds to perform can be stuffed into the jobs table. Job objects are serialized to yaml so that they can later be resurrected by the job runner.\n\n```ruby\nNewsletterJob = Struct.new(:text, :emails) do\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\nend\n\nDelayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.pluck(:email))\n```\n\nTo set a per-job max attempts that overrides the Delayed::Worker.max_attempts you can define a max_attempts method on the job\n\n```ruby\nNewsletterJob = Struct.new(:text, :emails) do\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\n\n  def max_attempts\n    3\n  end\nend\n```\n\nTo set a per-job max run time that overrides the Delayed::Worker.max_run_time you can define a max_run_time method on the job\n\nNOTE: this can ONLY be used to set a max_run_time that is lower than Delayed::Worker.max_run_time. Otherwise the lock on the job would expire and another worker would start the working on the in progress job.\n\n```ruby\nNewsletterJob = Struct.new(:text, :emails) do\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\n\n  def max_run_time\n    120 # seconds\n  end\nend\n```\n\nTo set a per-job default for destroying failed jobs that overrides the Delayed::Worker.destroy_failed_jobs you can define a destroy_failed_jobs? method on the job\n\n```ruby\nNewsletterJob = Struct.new(:text, :emails) do\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\n\n  def destroy_failed_jobs?\n    false\n  end\nend\n```\n\nTo set a default queue name for a custom job that overrides Delayed::Worker.default_queue_name, you can define a queue_name method on the job\n\n```ruby\nNewsletterJob = Struct.new(:text, :emails) do\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\n\n  def queue_name\n    'newsletter_queue'\n  end\nend\n```\n\nOn error, the job is scheduled again in 5 seconds + N ** 4, where N is the number of attempts. You can define your own `reschedule_at` method to override this default behavior.\n\n```ruby\nNewsletterJob = Struct.new(:text, :emails) do\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\n\n  def reschedule_at(current_time, attempts)\n    current_time + 5.seconds\n  end\nend\n```\n\nHooks\n=====\nYou can define hooks on your job that will be called at different stages in the process:\n\n\n**NOTE:** If you are using ActiveJob these hooks are **not** available to your jobs. You will need to use ActiveJob's callbacks. You can find details here https://guides.rubyonrails.org/active_job_basics.html#callbacks\n\n```ruby\nclass ParanoidNewsletterJob \u003c NewsletterJob\n  def enqueue(job)\n    record_stat 'newsletter_job/enqueue'\n  end\n\n  def perform\n    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }\n  end\n\n  def before(job)\n    record_stat 'newsletter_job/start'\n  end\n\n  def after(job)\n    record_stat 'newsletter_job/after'\n  end\n\n  def success(job)\n    record_stat 'newsletter_job/success'\n  end\n\n  def error(job, exception)\n    Airbrake.notify(exception)\n  end\n\n  def failure(job)\n    page_sysadmin_in_the_middle_of_the_night\n  end\nend\n```\n\nGory Details\n============\nThe library revolves around a delayed_jobs table which looks as follows:\n\n```ruby\ncreate_table :delayed_jobs, :force =\u003e true do |table|\n  table.integer  :priority, :default =\u003e 0      # Allows some jobs to jump to the front of the queue\n  table.integer  :attempts, :default =\u003e 0      # Provides for retries, but still fail eventually.\n  table.text     :handler                      # YAML-encoded string of the object that will do work\n  table.text     :last_error                   # reason for last failure (See Note below)\n  table.datetime :run_at                       # When to run. Could be Time.zone.now for immediately, or sometime in the future.\n  table.datetime :locked_at                    # Set when a client is working on this object\n  table.datetime :failed_at                    # Set when all retries have failed (actually, by default, the record is deleted instead)\n  table.string   :locked_by                    # Who is working on this object (if locked)\n  table.string   :queue                        # The name of the queue this job is in\n  table.timestamps\nend\n```\n\nOn error, the job is scheduled again in 5 seconds + N ** 4, where N is the number of attempts or using the job's defined `reschedule_at` method.\n\nThe default `Worker.max_attempts` is 25. After this, the job is either deleted (default), or left in the database with \"failed_at\" set.\nWith the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.\n\nThe default `Worker.max_run_time` is 4.hours. If your job takes longer than that, another computer could pick it up. It's up to you to\nmake sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.\n\nBy default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set\n`Delayed::Worker.destroy_failed_jobs = false`. The failed jobs will be marked with non-null failed_at.\n\nBy default all jobs are scheduled with `priority = 0`, which is top priority. You can change this by setting `Delayed::Worker.default_priority` to something else. Lower numbers have higher priority.\n\nThe default behavior is to read 5 jobs from the queue when finding an available job. You can configure this by setting `Delayed::Worker.read_ahead`.\n\nBy default all jobs will be queued without a named queue. A default named queue can be specified by using `Delayed::Worker.default_queue_name`.\n\nIf no jobs are found, the worker sleeps for the amount of time specified by the sleep delay option. Set `Delayed::Worker.sleep_delay = 60` for a 60 second sleep time.\n\nIt is possible to disable delayed jobs for testing purposes. Set `Delayed::Worker.delay_jobs = false` to execute all jobs realtime.\n\nOr `Delayed::Worker.delay_jobs` can be a Proc that decides whether to execute jobs inline on a per-job basis:\n\n```ruby\nDelayed::Worker.delay_jobs = -\u003e(job) {\n  job.queue != 'inline'\n}\n```\n\nYou may need to raise exceptions on SIGTERM signals, `Delayed::Worker.raise_signal_exceptions = :term` will cause the worker to raise a `SignalException` causing the running job to abort and be unlocked, which makes the job available to other workers. The default for this option is false.\n\nHere is an example of changing job parameters in Rails:\n\n```ruby\n# config/initializers/delayed_job_config.rb\nDelayed::Worker.destroy_failed_jobs = false\nDelayed::Worker.sleep_delay = 60\nDelayed::Worker.max_attempts = 3\nDelayed::Worker.max_run_time = 5.minutes\nDelayed::Worker.read_ahead = 10\nDelayed::Worker.default_queue_name = 'default'\nDelayed::Worker.delay_jobs = !Rails.env.test?\nDelayed::Worker.raise_signal_exceptions = :term\nDelayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', 'delayed_job.log'))\n```\n\nCleaning up\n===========\nYou can invoke `rake jobs:clear` to delete all jobs in the queue.\n\nHaving problems?\n================\nGood places to get help are:\n* [Google Groups](http://groups.google.com/group/delayed_job) where you can join our mailing list.\n* [StackOverflow](http://stackoverflow.com/questions/tagged/delayed-job)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcollectiveidea%2Fdelayed_job","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcollectiveidea%2Fdelayed_job","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcollectiveidea%2Fdelayed_job/lists"}