Rails定期任务 [英] rails periodic task

查看:64
本文介绍了Rails定期任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ruby on rails应用程序,试图在其中寻找一种每隔几秒钟运行一些代码的方法.

I have a ruby on rails app in which I'm trying to find a way to run some code every few seconds.

我已经发现许多使用cron或类似cron的实现的信息和想法,但是这些信息直到现在都是准确的,并且/或者需要外部工具.我想每15秒钟左右启动一次任务,并且希望它完全独立于应用程序(如果应用程序停止,则任务停止,并且没有外部设置).

I've found lots of info and ideas using cron, or cron-like implementations, but these are only accurate down to the minute, and/or require external tools. I want to kick the task off every 15 seconds or so, and I want it to be entirely self contained within the application (if the app stops, the tasks stop, and no external setup).

这用于后台生成缓存数据.每隔几秒钟,该任务将组装一些数据,然后将其存储在缓存中,该缓存将被所有客户端请求使用.该任务非常缓慢,因此它需要在后台运行,而不是阻止客户端请求.

This is being used for background generation of cache data. Every few seconds, the task will assemble some data, and then store it in a cache which gets used by all the client requests. The task is pretty slow, so it needs to run in the background and not block client requests.

我对ruby还是很陌生,但是有很强的perl背景,而我要解决的方法是创建一个时间间隔计时器&派生,运行代码并在完成后退出的处理程序.
仅仅模拟一个客户请求,并让rails控制器派生自己,可能会更好.这样,我可以通过点击URI来启动该任务(尽管由于该任务每隔几秒钟就会运行一次,所以我怀疑我是否需要这样做,但将来可能会使用它).尽管让控制器调用定期任务调度程序正在调用的任何方法(虽然我有一个方法)都是微不足道的.

I'm fairly new to ruby, but have a strong perl background, and the way I'd solve this there would be to create an interval timer & handler which forks, runs the code, and then exits when done.
It might be even nicer to just simulate a client request and have the rails controller fork itself. This way I could kick off the task by hitting the URI for it (though since the task will be running every few seconds, I doubt I'll ever need to, but might have future use). Though it would be trivial to just have the controller call whatever method is being called by the periodic task scheduler (once I have one).

推荐答案

通常来说,我所知道的没有内置的方法可以在应用程序中创建定期任务. Rails是基于Rack构建的,它期望接收http请求,执行某些操作,然后返回.因此,您只需要自己在外部管理定期任务即可.

Generally speaking, there's no built in way that I know of to create a periodic task within the application. Rails is built on Rack and it expects to receive http requests, do something, and then return. So you just have to manage the periodic task externally yourself.

我认为,鉴于您需要执行任务的频率,一个不错的解决方案可能是为自己编写一个永久循环的简单rake任务,并在启动应用程序的同时使用某种方法将其启动像工头工头经常像这样用于管理后台工作人员及其应用程序的启动/关闭.在生产中,您可能需要使用其他方法来管理流程,例如Monit.

I think given the frequency that you need to run the task, a decent solution could be just to write yourself a simple rake task that loops forever, and to kick it off at the same time that you start your application, using something like Foreman. Foreman is often used like this to manage starting up/shutting down background workers along with their apps. On production, you may want to use something else to manage the processes, like Monit.

这篇关于Rails定期任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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