[英]How can I use clockwork to input data every hour?
我的環境是帶有Ruby 2.0和Rails 4的Macbook OSX 10.7 Lion。
我是RoR的新手。 我使用腳手架建立了一個帶有一個列數據庫的網站。
這只是一個關於天氣的小網站。
我想每小時輸入一次數據庫。
我找到了寶石發條 ,但我不知道如何在我的項目中使用它。
我寫了clock.rb
並把它放在我的項目文件中並運行rails s
但沒有任何反應。
這是myproject / clock.rb
MyProject的/ clock.rb
require 'clockwork'
module Clockwork
handler do |job|
puts "Running #{job}"
every(1 hours, ''){
Mydata.create(:degree => input_data)
}
end
我應該怎么做或者我應該把文件放在哪里?
他們說我需要使用$ clockwork clock.rb
,但是當我運行rails s
,沒有辦法使用它...
非常感謝。
正如官方文檔中所述,您需要做一些事情。
設置時鍾文件,我在app/clock.rb
設置它
需要'發條'模塊發條
handler do |job| case job when 'weather.input_degree' Mydata.create degree: input_data # when 'some_other_task' # ... else puts "Couldn't find your job!" end end every(1.hour, 'weather.input_degree') # the string indicates an arbitrary job name # every(20.seconds, 'weather.some_other_task')
結束
啟動過程。 關鍵是使用像Foreman這樣的東西
$ gem安裝工頭
在應用程序的根目錄中創建一個名為Procfile
的文件:
web: bundle exec rails -s
clock: bundle exec clockwork app/clock.rb
# any_other_service_you_want: bash script here
啟動你的服務器
$工頭開始
gem 'clockwork'
例
在/ lib目錄下創建一個文件clock.rb
clock.rb
require File.expand_path('../../config/boot', __FILE__)
require File.expand_path('../../config/environment', __FILE__)
require 'clockwork'
include Clockwork
module Clockwork
## Here Student is a domain class, having a method insertRecord to
## insert a record in DB
every(20.seconds, 'job Inserting Record in DB') { Student.insertRecord }
end
命令運行時鍾字
bundle exec clockwork lib/clock.rb
你可以利用Cron 。 編寫一個rake任務並從Cron調用rake任務以重復進程。
示例(將其添加到cron以每小時運行一次任務):
0 * * * * cd /home/projectdir;rake do:task
此代碼需要保留在處理程序塊之外:
every(1.hour, ''){ Mydata.create(:degree => input_data) }
你可以這樣執行時鍾:
bundle exec clockwork clock.rb
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.