title: Rails Initializer: An infinite loop in a separate thread to update records in the background
body: <p>I want to run an infinite loop on a separate thread that starts as soon as the app initializes (in an initializer). Here's what it might look like:</p>
  
  <pre><code># in config/initializers/item_loop.rb
  
  Thread.new
    loop do
      Item.find_each do |item|
        # Get price from third-party api and update record.
        item.update_price!
        # Need to wait a little between requests to avoid getting throttled.
        sleep 5
      end
    end
  end
  </code></pre>
  
  <p>I tend to accomplish this by running batch updates in recurring background jobs. But this doesn't make sense since I don't really need parallelization, downtime, or queueing, I just want to update one item at a time in a single thread, forever.</p>
  
  <p>Yet there are multiple things that concern me:</p>
  
  <ol>
  <li><strong><a href="https://bibwild.wordpress.com/2014/07/17/activerecord-concurrency-in-rails4-avoid-leaked-connections/" rel="nofollow noreferrer">Leaked Connections</a></strong>: Should I open up a new <code>connection_pool</code> for the thread? Should I use a gem like <a href="https://github.com/ankane/safely" rel="nofollow noreferrer">safely</a> to avoid crashing the thread?</li>
  <li><strong><a href="https://www.engineyard.com/blog/a-modern-guide-to-threads" rel="nofollow noreferrer">Thread Safety</a></strong>: Should I be worried about race conditions? Should I make use of <code>Mutex</code> and <code>synchronize</code>? Does using <code>ActiveRecord::Base.transaction</code> impact thread safety?</li>
  <li><strong><a href="https://bibwild.wordpress.com/2016/12/29/concurrency-in-rails-5-0/" rel="nofollow noreferrer">Deadlock</a></strong>: Should I use <code>Rails.application.executor.wrap</code>?</li>
  <li><strong><a href="http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/TimerTask.html" rel="nofollow noreferrer">Concurrent Ruby/Sleep Intervals</a></strong>: Should I use <code>TimerTask</code> from <code>concurrent-ruby</code> gem instead of <code>sleep</code> or something other than <code>Thread.new</code>?</li>
  </ol>
  
  <p>Information on any of these subjects is appreciated.</p>