##Introduction to Background Workers
#####Repository
git clone https://github.com/turingschool-examples/loremore.git background_workers
###Procedure
- Overall overview.
- Explain what a background worker is.
- Explain what is a job.
- Explore the app.
- Click on
generate
quotes and observe the delay. - Create Job.
- Run
rails g job generate_quotes
. - Explain the structure of a job class.
- Replace controller code with job.
- Explain that if an adapter is not set the job is performed immediately.
- Add Adapter.
- Add sidekiq gem.
- Add
config.active_job.queue_adapter = :sidekiq
to application.rb. - Add
require ‘sidekiq/web’
to routes.rb. - Add
mount Sidekiq::Web, at: ‘/sidekiq’
to routes. - Add
gem sinatra
to Gemfile. - Start workers.
- Restart the server and open the dashboard (go to
/sidekiq
). - Launch sidekiq with
bundle exec sidekiq
.
- Scheduling a job.
- Use
.set(wait: 1.minute)
in job. - use
.set(wait_until: Time.current.next_week)
in job. - Show the dashboard.
- Foreman
- Add gem.
- Create Procfile.
- Add web and workers process.
- Run
foreman start
.
Workshop
Workshop 1: Creating a Job
Right now, the book titles are generated synchronously and the user perceives a delay. Open the BooksController and find the Book.generate method. Can you create a job that would handle this method?
Implementation
app/jobs/generate_quotes_job.rb
class GenerateQuotesJob < ActiveJob::Base
queue_as :default
def perform
Quote.generate
end
end
app/controllers/quotes_controller.rb
class QuotesController < ApplicationController
def index
@quotes = Quote.all
end
def create
GenerateQuotesJob.set(wait_until: Time.current.next_week).perform_later
redirect_to :back, success: 'The quotes were generated successfully.'
end
end
app/config/routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
mount Sidekiq::Web, at: '/sidekiq'
root 'site#show'
resources :books, only: [:index, :create]
resources :quotes, only: [:index, :create]
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.4'
gem 'sqlite3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'bootstrap-sass', '~> 3.3.5'
gem 'faker', '~> 1.5.0'
gem 'sidekiq', '~> 3.5.0'
gem 'sinatra'
gem 'foreman'
group :development, :test do
gem 'pry'
gem 'better_errors'
gem 'binding_of_caller'
end
Procfile
web: bundle exec rails s
workers: bundle exec sidekiq