Sam Lim
Sam Lim

Reputation: 197

Asynchronous API call to update model in Rails

I am making a simple API call to Coinbase's API to get the current buy/sell price of bitcoin. I have a before_save action on my Price model

class PriceBtc < ApplicationRecord
before_save :save_prices

def save_prices
    self.buy = PriceBtc.get_buy_price
    self.sell = PriceBtc.get_sell_price
  end
end

How can I trigger a new model creation every few seconds? I can't find anything on ActiveJob to do something in such a fast way. I tried the whenever gem to automatically set up CRON jobs but I could only get it to perform the task every 1 minute, when I'd like it to be every 3 seconds

Upvotes: 1

Views: 665

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33460

By using the rufus-scheduler gem:

Add the gem, bundle, and restart the server:

# Gemfile
gem 'rufus-scheduler'

Create the initializer:

# config/initializers/scheduler.rb
require 'rufus-scheduler'

scheduler = Rufus::Scheduler::singleton

count = 0
scheduler.every '5s' do
  Price.create price: count
  count += 1
end

Whenever you edit that file, you must restart the server. There is only creating a new Price record for each 5 seconds and setting the price to the value of count. Of course yours will be more useful than mine.

Upvotes: 2

Related Questions