Anushka
Anushka

Reputation: 61

How do I call a function at fixed intervals?

I want to call a particular function every five minutes.

I accumulate data in a string variable and then I want a function to process it.

How do I do it in Ruby?

Upvotes: 1

Views: 1026

Answers (2)

shawnzhu
shawnzhu

Reputation: 7585

Here's one example by providing a poison to enable/disable your function calls in another thread:

poison = false

t = Thread.new do
  loop do
    break if poison
    your_method(args)
    sleep(5.minutes)
    redo
  end
end
# uncomment the next line if this is your main thread
#t.join

Upvotes: 3

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22296

Check the rufus-scheduler:

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.in '5m' do
  your_method(args)
end

scheduler.join
  # let the current thread join the scheduler thread

Upvotes: 3

Related Questions