title: Run scripts in parallel in ruby
body: <p>I need to convert videos in 4 threads</p>
  
  <p>For example I have Active Record models Video with titles: Video1, Video2, Video3, Video4, Video5</p>
  
  <p>So, I need to execute something like this</p>
  
  <pre><code>bundle exec script/video_converter start
  </code></pre>
  
  <p>Where script will process unconverted videos for 4 threads, for example </p>
  
  <pre><code>Video.where(state: 'unconverted').first.process
  </code></pre>
  
  <p>But if one of 4 videos are converted, next video must be automatically added to thread</p>
  
  <p>What is the best solution for this ? Sidekiq gem? Daemons gem + Ruby Threads manually?</p>
  
  <p>For now I am using this script:</p>
  
  <pre><code>THREAD_COUNT = 4
  SLEEP_TIME = 5
  logger = CONVERTATION_LOG
  spawns = []
  loop do
    videos = Video.where(state:'unconverted').limit(THREAD_COUNT).reorder("ID DESC")
    videos.each do |video|
      spawns &lt;&lt; Spawnling.new do
        result = video.process
        if result.nil?
          video.create_thumbnail!
        else
          video.failured!
        end
      end
    end
    Spawnling.wait(spawns)
    sleep(SLEEP_TIME)
  end
  </code></pre>
  
  <p>But this script waits 4 videos, and after it takes another 4 videos. I want, that after one of 4-th video converted, it will be automatically added to new thread, which is empty.</p>