--- title: 12th 鐵人賽 Day_23 active job tags: 12th 鐵人賽 --- # 12th 鐵人賽 Day_23 active job ? 嗨!各位朋友大家好,打給後,歹嘎吼,胎尬喉,我是阿圓,一樣有請今天的one piece:  (這真的是我看得很感動的一幕 π口π ) 今天來跟各位介紹一下 active job~ ## active job ? 若今天想將一件事丟到背景工作去做,比如說寄一封歡迎或是驗證的email給使用者,或是過一段時間清除使用者的session,像這種可以丟到後面處理的任務,我們就會用 active job 來處理。 ## 產生 job ? 可以用產生器產生: `bin/rails g job user_welcome_email` 這樣就會在`app/jobs`裡產生一個`user_confirm_email_job.rb` 也可以直接建立檔案的方式產生,只要確認 class 是繼承自 ApplicationJob 的class。 而`.rb`檔的內容為: ```ruby= class UserWelcomeEmailJob < ApplicationJob queue_as :default def welcome(user) # 寄發歡迎信 end end ``` 其中的`queue_as`,指的是這件任務的優先程度,分別有:`:low_priority`(低),`:default`(預設),`:urgent`(高,可插隊) 以上方程式碼為例,`welcome` 接收一個`user` 物件,然後發送歡迎信,接著就可以在 Controller 中,指定成當user建立後,發送歡迎信: ```ruby= class UsersController < ApplicationController # ...[略]... def create @user = User.new(user_params) if @user.save UserWelcomeEmailJob.welcome_later(@user) redirect_to @user, notice: 'User was successfully created.' else render :new end end # ...[略]... end ``` 其中 ```ruby= UserWelcomeEmailJob.welcome_later(@user) ``` 就是發送一個job,丟到背景做,至於`welcome_later`就是等系統有空的時候在做,若有其他的設定: ```ruby= # 這樣是 5 秒之後做 UserWelcomeEmailJob.set(wait: 5.seconds).welcome_later(@user) # 這樣是「明天下午有空再做」 UserWelcomeEmailJob.set(wait_until: Date.tomorrow.noon).welcome_later(@user) ``` ## 背景工作? 所以這個 job 到底是丟到哪裡工作?預設會是主機的記憶體,但如果 job 尚在排隊中,還沒有執行,主機卻被重開機,這個時候所有的 job ,就都不見了,所以一般會將 job 存放在別的地方。 而最好設定的就是[Delayed Job](https://github.com/collectiveidea/delayed_job) 照頁面說明安裝後,他會建立一個存放 job 的資料表,裡面記錄了 job 的優先權、失效時間...等等等(請參考下圖),這樣就不怕重開機的時候 job 不見了。  除了`rails db:migrate`也別忘了去`app/configs/application.rb`中 加上: ```ruby= module MyBlog class Application < Rails::Application config.active_job.queue_adapter = :delayed_job end end ``` 將 job 指定給`delayed_job`透過資料表來存放! 以上就是今天的內容,感謝各位看到這邊,若有任何建議,請各位不吝指教!我們明天見! 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up