简体   繁体   中英

Keep getting Stack level too deep when calling API recursively

I am continuously calling an API and keep getting Stack level too deep error within minutes of call. I guess I am missing something basic here:

Class SomeModel

  def self.call_api(index)
    ref = SomeModel.get_reference
    query ||=  Api.call(:parameter => ref.parameter, :offset => index)
    # .. doing stuff
    if index >= 949
      sleep(20)
      new_num = Integer(number) + 1000
      ref.update_attribute(:parameter, new_num)      
      SomeModel.call_api(1)
     else
       sleep(10)
       begin
             # This is a rescue for the case when API call returns nothing.
         SomeModel.call_api(index+50)
       rescue
         new_num = Integer(number) + 1000
         ref.update_attribute(:parameter, new_num)
         SomeModel.call_api(1)
       end
    end
  end

end

Ruby does not handle recursion well and will always eventually give you a stack level too deep. You're better off putting this inside some sort of loop that does not call the method recursively. If you want it to be a little smarter than just calling the method in an infinite loop, you can use something like EventMachine to respond to different events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM