如何在rails上的ruby中自动执行代码? [英] How do I automate my code in ruby on rails?

查看:68
本文介绍了如何在rails上的ruby中自动执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Ruby on Rails应用程序,其中来自在线数据库的数据被拉出并存储在我的本地数据库中。但是,每次重新加载页面时都会发生此过程。



此外,我想创建一些东西(可能是超时),这样我就可以每隔一段时间运行代码(例如2分钟)。我不知道该怎么做。



谢谢。



我有什么尝试过:



我不知道从哪里开始,因此我还尝试过任何东西。

I am creating a Ruby on Rails application where data from an online database is pulled and stored in my local database. However, this process only happens every time I re-load the page.

Moreover, I would like to create something (maybe a timeout), that would allow me to run the code every amount of time (2 minutes for example). I do not know how to do that.

Thank you.

What I have tried:

I do not know where to start, thus I have tried anything yet.

推荐答案

我用过这个:



I used this:

def show
  every_n_seconds (120) do
     #code to do
 end
end





一直到顶部,(以便ruby在其他任何事情之前看到这个方法),我有:





And all the way at the top, (so that ruby sees that method before anything else), I have:

def every_n_seconds(n)
    loop do
      before = Time.now
      yield
      interval = n-(Time.now-before)
      sleep(interval) if interval > 0
    end
  end





工作得很好。无论如何,谢谢大家。我希望这可以帮助将来的某个人。



It is working quite nice. Thanks everyone anyway. I hope this can help someone in the future.


这篇关于如何在rails上的ruby中自动执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆