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
Couldn't Require Openssl in Ruby
How to Know When to "Refresh" My Model Object in Rails
Guard with Rspec on Rails 4 Giving a Lot of Warnings
How to Run a Ruby Script Using Rbenv with Cron
Size, Length and Count in Rails
Creating a Model That Has a Tree Structure
Error: Failed to Build Gem Native Extension When Installing Rails on MAC Mountian Lion Os
Ruby: File Encryption/Decryption with Private/Public Keys
Confusion About Passing Instance Variables to Redirect_To Method. as Seen in Rails Guides
Rails 3.1 Pipeline - Exclude JavaScript File
In Ruby on Rails, After Send_File Method Delete the File from Server
How to Reference a Function in Ruby
Activerecord - Querying Polymorphic Associations
Best Practice for Rails App to Run a Long Task in the Background