Search code examples
ruby-on-railsrubyruby-on-rails-4cronwhenever

How to run a cron job every 10 seconds in ruby on rails


I am trying to run a cron job in every 10 seconds that runs a piece of code. I have used an approach which requires running a code and making it sleep for 10 seconds, but it seems to make drastically degrading the app performance. I am using whenever gem, which run every minute and sleeps for 10 seconds. How can I achieve the same w/o using sleep method. Following is my code.

every 1.minute do
  runner "DailyNotificationChecker.send_notifications"
end

class DailyNotificationChecker
    def self.send_notifications
        puts "Triggered send_notifications"
        expiry_time = Time.now + 57
        while (Time.now < expiry_time)
            if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
              process_notes
            end
          sleep 10 #seconds
        end

    def self.process_notes
        notes = nil
        time = Benchmark.measure do
          Note.uncached do
            notes = Note.where(status: false)
            notes.update_all(status: true)
          end
        end
        puts "time #{time}"
      end
    end

Objective of my code is to change the boolean status of objects to true which gets checked every 10 seconds. This table has 2 million records.


Solution

  • You would use the clockwork gem. It runs in a separate process. The configuration is pretty simple.

    require 'clockwork'
    include Clockwork
    
    every(10.seconds, 'frequent.job') { DailyNotificationChecker.process_notes }