从配置文件调用模型
我正在编写一个 ruby 调度程序 - 即 rufus-scheduler,我需要在 config 文件夹内的初始化程序部分编写一些命令,以便每 1 分钟左右执行一次任务。我正在尝试从其中的模块访问方法。所以我的代码看起来像这样,
scheduler.every("1m") do
puts("HELLO #{Time.now}")
ModelName.methodname("WHAT ARE YOU DOING")
end
这在某种程度上不会在模型中执行必要的操作。我也不确定这是否是正确的做法 - 例如在配置文件中调用模型。有没有更好的地方可以将此代码放在模型中?或者在配置文件中调用模型是一个很好的实践。我在互联网上查看了 ruby 中不同类型文件的用法,但找不到合适的材料。任何帮助或指导表示赞赏。
I am writing a ruby scheduler - namely rufus-scheduler and there are commands i need to write in the initializers section inside the config folder to perform a task every 1 minute or so. I am trying to access a method from a module within this. So my code would look like
scheduler.every("1m") do
puts("HELLO #{Time.now}")
ModelName.methodname("WHAT ARE YOU DOING")
end
This somehow doesn't perform the necessary operation in the model. Also im not sure if this is the right way to do things - such as call a model inside a config file. Is there a better place to put this code in the Model? Or is calling a Model within config files perfectly good practice. I looked over the internet to see the usage of different types of files in ruby but couldn't find a proper material. Any help or guidance appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想从独立任务访问模型,最好的方法是使用
rails runner
包装器。例如,您可以将脚本称为:这会在 Rails 环境中加载,然后执行您的脚本,从而无需您自己执行此操作。模型本身无法工作,因为它们缺乏 Rails 的上下文。
如果这还不够,您可能需要通过将 config/environment.rb 包含到 rufus-scheduler 配置中来更直接地加载 Rails 环境。
If you want to access models from stand-alone tasks the best way is to use the
rails runner
wrapper. For example, you'd call your script as:This loads in the Rails environment and then executes your script, eliminating the need to do that yourself. Models on their own will not work since they are lacking the context of Rails.
If that's not sufficient, you may need to load the Rails environment more directly by including
config/environment.rb
into your rufus-scheduler configuration.听起来您实际上想要某种真正的预定操作。配置文件用于配置,而不是用于此类实际工作代码。
在 Rails 中运行计划任务的方法有很多。
谷歌“rails守护进程”或“rails计划任务”来开始你的工作。
以下是使用 cron 的计划任务最佳实践的一个很好的列表:
rails 的 cron 作业:最佳实践?
It sounds like you actually want a real scheduled action of some sort. config files are for configuration, not for actual working code of that sort.
There are tons of ways to run scheduled tasks in rails.
google "rails daemons" or "rails scheduled tasks" to start you off.
Here's a good list of scheduled-task best practices using cron:
A cron job for rails: best practices?