Search code examples
ruby-on-railsrubywebsocketactioncable

Execute a function when a time is equal to a certain value in Rails 6


I am building an online e-commerce store, and I am trying to use rails with action cable to update a product from being out of stock to in-stock at a certain date time e.g 12:00:00 2020-02-19.

The idea is as soon as the time is reached, I want to push a Websocket that the product is now available.

I have tried a few solutions such as:

  Thread.new do
    while true do
      if **SOMETIME** == Time.now
        ActionCable.server.broadcast "product_channel",content: "product-in-stock"
      end
    end
  end

The main issue with this approach is that it creates another thread and makes rails unresponsive. Furthermore, if this value is set for say 1 week from now I do not want every user who queries the endpoint to create a brand-new thread running like this.


Solution

  • You have two option use sidekiq jobs or use whenever job gem https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs Whenever allow you to set specific day and time, check the documentation for more info https://github.com/javan/whenever