From 40939795096c0b7a1791d71d920b84ff283fb550 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Fri, 25 Apr 2014 11:09:09 -0400 Subject: Sampling methods WIP --- lib/throttled_api_request.rb | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 lib/throttled_api_request.rb (limited to 'lib/throttled_api_request.rb') diff --git a/lib/throttled_api_request.rb b/lib/throttled_api_request.rb new file mode 100644 index 0000000..3f30c56 --- /dev/null +++ b/lib/throttled_api_request.rb @@ -0,0 +1,25 @@ +class ThrottledApiRequest < Struct.new(:api_name, :unit_time, :requests_per) + def before(job) + loop do + sleep_for = -1 + ActiveRecord::Base.transaction do + ApiRequests.create(:api_name => self.api_name) + recent_requests = ApiRequets. + where(:api_name => self.api_name). + where("updated_at > ?", Time.now.utc - self.unit_time). + order(:updated_at) + if (recent_requests.count > self.requests_per) + sleep_for = Time.now.utc - recent_requests[recent_requests.count-self.requests_per].updated_at + raise ActiveRecord::Rollback + else + sleep_for = -1 + end + end + if sleep_for != -1 + sleep(sleep_for) + else + break + end + end + end +end -- cgit v1.2.3-54-g00ecf