Background Workers
##Introduction to Background Workers
#####Repository
git clone https://github.com/turingschool-examples/loremore.git background_workers
###Procedure
generate
quotes and observe the delay.rails g job generate_quotes
.config.active_job.queue_adapter = :sidekiq
to application.rb.require ‘sidekiq/web’
to routes.rb.mount Sidekiq::Web, at: ‘/sidekiq’
to routes.gem sinatra
to Gemfile./sidekiq
).bundle exec sidekiq
..set(wait: 1.minute)
in job..set(wait_until: Time.current.next_week)
in job.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