Ruby 中有类似定时器的东西吗

Is There Anything Like Timer in Ruby

这是我需要的 -

def get_file_from_web()
    # This is a function which retries the following function when that function is not completed with in 1 min.
    timer(60)
    # This method is use to connect to internet and get the file specified and i should not take more than 1 min. 
    file = get_file()
end

请大家帮我解决这个问题。我需要一个计时器在指定时间后触发一个动作。

此代码将在失败前尝试获取文件 3 次。 get_file 方法包含在 Timeout.timeout 块中,如果完成时间超过 60 秒,它将引发 Timeout::Error。如果引发超时错误,我们要么重试操作,要么根据是否还有更多重试次数重新引发错误。

require 'timeout'

def get_file_from_web
  retries = 3
  begin
    Timeout.timeout(60) { get_file() }
  rescue Timeout::Error
    if (retries -= 1) > 0
      retry 
    else
      raise
    end
  end
end

您还可以使用 retryable 来减少所需的代码量。

require 'timeout'

def get_file_from_web
  Retryable.retryable(tries: 3, on: Timeout::Error) do
    Timeout.timeout(60) { get_file() }
  end
end