Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby on rails

How to enqueue a job in Ruby on Rails

Khizar Hayat Saani

A job in Ruby on Rails (RoR) is any process that can be decomposed into smaller units of work. This allows the job to be run in parallel with other jobs to decrease our overall execution time.

Jobs in Ruby on Rails

Creating jobs

Jobs are declared using the Active Job framework. The jobs can then be run on multiple queueing backends.

Here’s how we create a job using Active Job:

bin/rails generate job my_job

We have successfully generated a job titled my_job.

Enqueue jobs

Jobs can be enqueued and executed after we have successfully configured our queueing backend.

Enqueueing a job is basically placing the job in a queue where it waits for execution. We can also explicitly set times for when a job should be performed. The different enqueuing options are the following:

  • wait: With this, the job is enqueued after the mentioned time period
  • wait_until: With this, the job is enqueued after that the specified time has elapsed
  • queue: With this, the job is added to the specified queue.
  • priority: With this, the job is enqueued with the defined priority.

The following example enqueues our job (my_job) to be performed 1 week from now:

MyJob.set(wait: 1.week).perform_later(guest)

The following example enqueues our job (my_job) as soon as the queueing system is free:

MyJob.enqueue guest

The following example enqueues our job (my_job) at noon the following day.

MyJob.enqueue(wait_until: Date.tomorrow.noon).perform_later(guest)

Note: Ruby on Rails commands are run on your terminal.

RELATED TAGS

ruby on rails

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring