[英]How can I use clockwork to input data every hour?
My environment is Macbook OSX 10.7 Lion with Ruby 2.0 and Rails 4. 我的环境是带有Ruby 2.0和Rails 4的Macbook OSX 10.7 Lion。
I am new to RoR. 我是RoR的新手。 I built a website with one column database using a scaffold. 我使用脚手架建立了一个带有一个列数据库的网站。
It's just a little website about weather. 这只是一个关于天气的小网站。
I want to input degrees to database every hour. 我想每小时输入一次数据库。
And I found the gem clockwork , but I have no idea how to use it with my project. 我找到了宝石发条 ,但我不知道如何在我的项目中使用它。
I wrote clock.rb
and put it in my project file and ran rails s
but nothing happened. 我写了clock.rb
并把它放在我的项目文件中并运行rails s
但没有任何反应。
Here is myproject/clock.rb 这是myproject / clock.rb
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
What should I do with it or where should I put the file? 我应该怎么做或者我应该把文件放在哪里?
They say that I need to use $ clockwork clock.rb
, but when I run rails s
, there's no way to use that... 他们说我需要使用$ clockwork clock.rb
,但是当我运行rails s
,没有办法使用它...
Thanks a lot. 非常感谢。
As stated in the official docs you need a couple of things. 正如官方文档中所述,您需要做一些事情。
setup the clock file, I've set it in app/clock.rb
设置时钟文件,我在app/clock.rb
设置它
require 'clockwork' module Clockwork 需要'发条'模块发条
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')
end 结束
The starting process. 启动过程。 The key is to use something like Foreman 关键是使用像Foreman这样的东西
$ gem install foreman $ gem安装工头
Create a file named Procfile
in root of your app: 在应用程序的根目录中创建一个名为Procfile
的文件:
web: bundle exec rails -s
clock: bundle exec clockwork app/clock.rb
# any_other_service_you_want: bash script here
start your server 启动你的服务器
$ foreman start $工头开始
gem 'clockwork'
Example 例
Create a file clock.rb under /lib directory 在/ lib目录下创建一个文件clock.rb
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
Command to Run the clockword 命令运行时钟字
bundle exec clockwork lib/clock.rb
This code needs stay outside of handler block: 此代码需要保留在处理程序块之外:
every(1.hour, ''){ Mydata.create(:degree => input_data) }
You can execute the clock like that: 你可以这样执行时钟:
bundle exec clockwork clock.rb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.