Perform Some Task After View Render Using Threads In Rails

Posted By Weston Ganger

I wanted an easy way to run some expensive tasks after my controller rendered the view so that the user can continue on while the work is done. While most of the time you can use ActiveJob or something to do this, this technique can come in handy.

Turns out we can easily do this by creating a new Thread. Here I show using with render or redirect_to

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
    render
    Thread.new do
      my_expsenive_method(@post)

      Thread.exit
    end
  end

  def update
    @post = Post.find(params[:id])
    @post.update_attributes(post_params)
    redirect_to action: :index
    Thread.new do
      my_expsenive_method(@post)

      Thread.exit
    end
  end
end

This works like a charm however this technique should only be used in non-critical code because Threads have many quirks to them. For example you will not easily be able get any data back from this new thread and it also will not show any errors to your users if it fails.

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:July 21, 2016