Sometimes a specific piece of code takes a long time to run but doesn’t need to run right away. An example is sending an e-mail after creating an order at the end of an online shopping workflow. It can take a long time to send an e-mail, but you don’t want your user to wait for that to happen within the controller. It makes more sense to use a queueing mechanism for these tasks.
Active Job provides such a queueing system. You can create jobs that are processed asynchronously by the active job.
Create a New Job
The quickest way to create a new job is to use the job generator. Let’s create an example job that waits for ten seconds and then logs an info message, as shown here:
All jobs are created in the app/jobs directory. Please change the app/jobs/example_job.rb file accordingly, as shown in Listing 10-1.
app/jobs/example_job.rb
You can test the job in your console with ExampleJob.perform_later, which creates it.
Now you have to wait ten seconds to see the following output in the console:
The file log/development.log contains the logging output.
You’ll find a more concrete example of using jobs in Chapter 11 where an e-mail gets sent.
Set the Time for Future Execution
wait
ExampleJob.set(wait: 1.hour).perform_laterwait_until
ExampleJob.set(wait_until: Date.tomorrow.noon).perform_later
Configure the Job Server Back End
The page http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html lists all the available back ends. To use one of them, you have to install the needed gem. Listing 10-2 shows an example of using the popular Sidekiq . To use the gem, you have to add it to the Gemfile and run a bundle install command afterward.
Gemfile
In config/application.rb, you can configure the use of it, as shown in Listing 10-3.
config/application.rb