我是新手。我有问题,我在Ruby on Rails上构建了Web使用。我想从json文件中获取数据,然后插入数据库中。json文件中的数据可以随时增加。因此,我应该有一个后台作业,以一定的间隔运行。我已经阅读了Ruby文档,并说我可以使用Active Job。但是我仍然感到困惑。我应该如何逐步实现它?还是你们可以举个例子?
不管怎么说,还是要谢谢你。
您可以使用ActiveJob
活动作业设置
活动作业适配器必须设置为:sidekiq,否则将仅使用默认的:inline。
可以在config / application.rb中这样完成:
例如:
class Application < Rails::Application
# ...
config.active_job.queue_adapter = :sidekiq
end
接下来,生成Job:
rails generate job Example
样本JSON数据:
{
"title" : "Ruby In Rails",
"url" : "http://rubyinrails.com",
"posts" : {
"1":"strftime-time-format-in-ruby",
"2":"what-is-gemset"
}
}
将创建/app/jobs/example_job.rb
class ExampleJob < ActiveJob::Base
# Set the Queue as Default
queue_as :default
def perform(*args)
# Perform Job
require 'json'
# Open JSON File
root = Rails.root.to_s
file = File.read('#{root}/data.json')
# Parse Data from File
data_hash = JSON.parse(file)
# Do the SAVING and validation HERE...
test = Sample.new
test.title = data_hash['title']
......
test.save
end
end
用法,例如 在控制器中:
ExampleJob.perform_later args
或者,如果您更喜欢使用 CRONJOB来实现该功能:
例如,在Rails应用程序的lib / tasks /中创建一个名为“ save_json.rb ”的文件。
代码:
namespace :save_json do
desc "..."
task :execute => :environment do
require 'json'
# Open JSON File
root = Rails.root.to_s
file = File.read('#{root}/data.json')
#Parse Data from File
data_hash = JSON.parse(file)
#Getting DATA
data_hash['title']
=> "Ruby In Rails"
data_hash.keys
=> ["title", "url", "posts"]
data_hash['posts']
=> { "1" => "strftime-time-format-in-ruby", "2" => "what-is-gemset" }
# Do the SAVING and validation HERE...
test = Sample.new
test.title = data_hash['title']
......
test.save
end
在crontab中设置后台作业功能。
vi /etc/crontab
代码:例如每分钟....
*/1 * * * * cd /my_rails_app && bundle exec rake save_json:execute
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句