如何将控制器方法作为后台任务运行?
我听说过各种后台任务工具(delayed_job、starling、workling 等),但从这些工具来看,它们似乎实际上只能运行基于模型的方法(例如 User.update_counters)。
我需要能够运行控制器方法,因为它是一组非常复杂的任务,与许多其他控制器方法和自定义类交织在一起。
这是一个 CPU 密集型进程,可能需要大约 5-10 分钟才能运行,因此我希望它运行时不会干扰其他用户的“正常”站点操作。
我是否误解了其他工具的工作原理?还是还有其他我没有考虑到的事情?
I've heard of the various background task tools (delayed_job, starling, workling, etc) but from looking at those it seems they're really only capable of running model-based methods (User.update_counters, for example).
I need to be able to run a controller method as it's a pretty complex set of tasks that's intertwined a slew of other controller methods and custom classes.
It's a CPU intensive process that can take ~5-10 minutes to run so I'd like it to run without interfering with "normal" site operations from other users.
Am I misunderstanding how those other tools work? Or is there something else I'm not considering?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可接受的处理方式是将所有复杂逻辑移至模型中,并让控制器仅指导请求和响应。这就是“胖模型和瘦控制器”理论所说的。将复杂的逻辑移至模型类(不一定是 ActiveRecord 类),并且您可能可以有一个由后台工具调用的 rake 任务。
The accepted way of doing things is to move all your complex logic in to the model and have the controller only to direct the requests and responses. This is what "Fat models and skinny controllers" theory says. Move the complex logic in to a model class (that doesn't necessary be an ActiveRecord class) and may be you can have a rake task to be called by a background tool.
如果您确实需要运行控制器操作,那么您可以使用 cron 和 wget 或 curl。但我建议将复杂的逻辑移至模型或库中,以便您可以使用您提到的后台工具之一在控制器外部调用它。
If you really need to run the controller action then you could use cron and wget or curl. But I'd recommend moving your complex logic out into a model or a library so you can then call it outside of the controller using one of the background tools you mention.
您可能需要考虑将这个复杂的任务转变为 rake 任务。您的 rake 任务仍然可以引用您的模型,因此建议您将尽可能多的相关逻辑推送到它们中。
此外,由于您说该任务受 CPU 限制,并且在执行时会减慢站点速度,因此您可以使用
nice
(假设您在 UNIX 系统上)来调整 rake 任务的优先级。You may want to consider turning this complex task into a rake task. Your rake tasks can still reference your models, so it is recommended that you push as much logic that is relevant into them.
Additionally, since you say that the task is CPU bound and is slowing the site when it executes you could use
nice
(assuming your on a UNIX system) to adjust the priority of your rake task.在这种情况下,我想说你的流程最好留在控制器之外。如果您的大型进程在运行时使整个系统陷入困境,那么我的第一个反应是假设我的进程没有需要的那么流畅。如果该过程确实如此密集以至于导致整个系统陷入困境,那么它是夜间过程或停机期间的主要候选者。
I'd say your process is best left outside the controller arena in this case. If you've got this large process that is bogging down the entire system when it runs, then my first response is to assume my process is not as slick as it needs to be. If indeed the process is so intensive that it bogs down the whole system, then it is a prime candidate for a nightly process or during downtime.