Ruby on Rails: How to Run Things in the Background

Ruby on Rails: How to run things in the background?

You should definitely check out the following Railscasts:

  • http://railscasts.com/episodes/127-rake-in-background
  • http://railscasts.com/episodes/128-starling-and-workling
  • http://railscasts.com/episodes/129-custom-daemon
  • http://railscasts.com/episodes/366-sidekiq

They explain how to run background processes in Rails in every possible way (with or without a queue ...)

Best approach to create a background task

Convert the specific tasks into background jobs, i.e. (active job, sideqik), so your system can continue working while it's doing the tasks. Create classes for each task and call those classes within your background jobs or cronjobs.
One design pattern that could fit here is the "command" pattern, I gave you a list of things you can Google :).

Execute a short background task in a rails controller

Starting a thread it not that bad for simple things, but you'll have to manually handle all possibilities of it going wrong (freezing, exceptions)

You might want to look into using sucker_punch ActiveJob backend - it runs tasks inprocess, but you'll have the benefits of activejob (easier testing, generators etc.) and ability to switch to other backend later, if needed.

Best practice for Rails App to run a long task in the background?

The Workling plugin allow you to schedule background tasks in a queue (they would perform the lengthy task). As of version 0.3 you can ask a worker for its status, this would allow you to display some nifty progress bars.

Another cool feature with Workling is that the asynchronous backend can be switched: you can used DelayedJobs, Spawn (classic fork), Starling...

How can I run a controller method as a background task?

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.



Related Topics



Leave a reply



Submit