How can I run a controller method as a background task?
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 inte开发者_运维知识库rfering with "normal" site operations from other users.
Am I misunderstanding how those other tools work? Or is there something else I'm not considering?
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.
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.
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.
精彩评论