skip to Main Content

I have a Ruby on Rails app. Ruby 2.3 Rails 3.2 The app uses resque which runs jobs asynchronously off a queue. One job, in particular, makes calls to an external (Ebay) api. While the api call is being made, the CPU of the ec2 instance doesn’t process anything. Is there a way to prevent the CPU from going idle during the api call?

2

Answers


  1. Chosen as BEST ANSWER

    Here's a solution I came up with which is working so far. I realize this question tends to offend peoples' sensibilities. But, perhaps with the caveat that this code should never actually be executed, I'd be interested to know of any potential shortcomings:

    module AppHelpers
      def self.prevent_idle_cpu
        uuid = SecureRandom.uuid
        cache_key = "/prevent_idle_cpu/#{uuid}"
        Rails.cache.write(cache_key, "busy", expires_in: 1.day)
        thread = Thread.new do
          while Rails.cache.read(cache_key).present?
            1_000_000.times { 13 * 13 }
          end
        end
        thread.priority = -1
        begin
          yield
        ensure
          Rails.cache.delete(cache_key)
        end
      end
    end
    
    AppHelpers.prevent_idle_cpu do
      api.make_call
    end
    

  2. Is there a way, with Ruby, to prevent the CPU from going idle without
    blocking anything?

    Yes absolutely. In fact its trivial:

    require 'securerandom'
    t = Thread.new do
      loop do
        print SecureRandom.alphanumeric(3)
        sleep 0.00001
      end
    end
    

    This will just continue printing a Matrix screensaver indefinately without blocking until you call t.exit.

    But its most likely the wrong answer to the wrong question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search