[Rails] About ActiveJob ,!

What is ActiveJob?

A framework for declaring jobs and thereby performing queue operations in different ways on the backend. By using Active Job, it is possible to send emails and execute batch processing in the background.

Active Job background

queue

First in, first out data structure. The reverse of the stack.

job

Starting with regular cleanups, invoicing, email delivery, and all other processing becomes a job. It is also possible to divide these jobs into smaller work units and execute them in parallel.

Purpose of Active Job

--You will be able to install job framework functions and other gems without worrying about the API differences of various job execution functions such as Delayed Job and Resque. --In the back-end queuing work, you don't have to worry about anything other than the operation method. --You don't have to rewrite the job when switching job management frameworks.

Resque --You can deploy code with memory leaks such as RMagick without any worries. --The ecosystem is complete. --Since it forks every time, it is suitable for long-time jobs. --Redis required for queue storage. --Maintenance is not catching up.

Delayed Job --DM needs to create a dedicated table. --If there is a code leaking memory, it needs to be restarted regularly.

Sidekiq --Resque compatible API. --Since it operates in parallel, it is convenient to use for applications where the ratio of I / O waiting is large, such as API calls to external sites. --Since it can be operated by one process, it uses less memory and is economical. --Weak against process bloat. --Handling of connection pools. --Handling other than parallel.

ActiveJob installation procedure

  1. Execute the following command to install.

$ brew install redis
  1. Add the following to the Gemfile.

gem 'resque'
gem 'resque-scheduler'

Also execute this.


$ bundle install
  1. Add the initialization file and rake task.

config/initializers/resque.rb



Resque.redis = Redis.new(host: 'localhost', post: 6379)
Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }
  1. Create a Request configuration file with the following contents.

lib/tasks/resque.rake



require 'resque/tasks'
require 'resque/scheduler/tasks'

namespace :resque do
  task setup: :environment do
    ENV['TERM_CHILD'] ||= '1'
    ENV['QUEUE'] ||= '*'
    require 'resque'
    require 'resque-scheduler'
  end
end
  1. Create the following initialization file and specify Resque as queue_adapter.

config/initializers/active_job.rb



ActiveJob::Base.queue_adapter = :resque

Actual usage example

--Send emails in the background using Active Job

  1. Create UserMailer with the following command.

$ rails g mailer user_mailer
  1. Add methods and views for submission.

app/mailers/user_mailer.rb



class UserMailer < ActionMailer::Base
  default from: "[email protected]"

  def registered(user)
    mail(to: user.email, subject: 'Welcome to Rdaily!')
  end
end

app/views/user_mailer/registered.text.erb



Dear. <%= @user.name %>

Welcome to Rdaily!
  1. Create a job with the following command

$ rails g job user_registered_mailer
  1. Edit the created file as follows.

app/jobs/user_registered_mailer_job.rb



class UserRegisteredMailerJob < ActiveJob::Base
  queue_as :email

  def perform(user)
    UserMailer.registered(user).deliver_now
  end
end
  1. To use the created job, create an instance of the job on the controller as shown below, specify the waiting time, and call the #perform_later method.

class Account::UsersController < ApplicationController
  ...

  def create
    @user = User.new(user_params)
    if @user.save
      UserRegisteredMailerJob.perform_later(@user)
      flash.notice = "User is successfully created."
      redirect_to account_path
  ...
end
  1. Add the following to the Gemfile.

gem 'mailcatcher'

Also execute this.


$ bundle install
  1. Write the following in the environment setting file.

config/environments/development.rb



Rails.application.configure do
  ...
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = { address: 'localhost', port: 1025 }
  ...
end
  1. Start mailcatcher with the following command.

$ mailcatcher
  1. Start various servers.

#Start the Redis server with the following command
$ redis-server

#Start Resque worker with the following command
$ bundle exec rake resque:work

#Launch Resque Scheduler
$ rake environment resque:scheduler

#Start Rails server
$ rails server

reference

Let's use Active Job introduced in Rails 4.2

[Rails, Linux] I tried to summarize "Active Job" and "Job"

Recommended Posts

[Rails] About ActiveJob ,!
About Rails 6
About Rails routing
About Rails controller
About RSpec (Rails)
[Rails] About migration files
[Rails] About active hash
About rails application server
About rails kaminari pagination
About rails version specification
MEMO about Rails 6 series
[Rails] About Slim notation
[rails] About devise defaults
Rails: About partial templates
About rails strong parameters
[Beginner] About Rails Session
about the where method (rails)
[Ruby on Rails] about has_secure_password
About naming Rails model methods
[Rails] About scss folder structure
About =
[Rails] About Rspec response test
About Rails scraping method Mechanize
[Rails] About the Punk List function
About the symbol <%%> in Rails erb
[Rails] About implementation of like function
[Rails] About helper method form_with [Basic]
Consideration about Rails and Clean Architecture
[Rails g.error]
About Kotlin
About attr_accessor
Rails basics
Rails Review 1
About Hinemos
[Rails] first_or_initialize
About params
rails tutorial
About form_for
About Spring ③
[Ruby on Rails] About bundler (for beginners)
About enum
[Rails 6.0] About batch saving of multiple records
Rails foundation
About Optional
About hashes
About JitPack
rails tutorial
About Dockerfile
rails tutorial
rails tutorial
About this ()
About devise
About encapsulation
About JAVA_HOME
About active_hash
[Ruby on Rails] About Active Record callbacks
About exceptions
[Rails] devise
Rails: A little summary about data types
rails tutorial
rails tutorial