2016-04-23 66 views
0

我使用twitter gem从我的应用程序调用API调用并获取一些数据。使用twitter gem进行并行调用

我有user_ids一个数组,我想通过做这样的事情来获取每个用户的所有微博:

user_ids.map {|user_id| Client.user_timeline(user_id)} 

有没有什么办法让这些电话并发?有什么方法可以使用typhoeus或者其他类似的twitter?有没有其他方法可以使此操作更快?

+0

考虑[单独的线程]让你的API调用(http://ruby-doc.org/core/Thread.html)。 – Uzbekjon

+0

@Uzbekjon我首先想到了使用线程,但我遇到了这个[问题](http://stackoverflow.com/questions/56087/does-ruby-have-real-multithreading)。当我使用CRuby时,我认为线程不会帮助我。如果我错了,请纠正我。 –

+0

不,那会工作得很好。您链接到的SO问题讨论了“真正的OS级多线程”。但是,你并不关心多线程是如何实现的,对。就其所做的工作而言。 – Uzbekjon

回答

1

环绕你的API调用在Ruby threads同时运行它们:

tweets, threads = [], [] 

threads = user_ids.map do |user_id| 
    Thread.new { tweets << Client.user_timeline(user_id) } 
end 

threads.each(&:join) 

# All the tweets are in the `tweets` array 
puts tweets