diff options
author | AndrewMurrell <amurrel@purdue.edu> | 2014-04-26 23:38:09 -0400 |
---|---|---|
committer | AndrewMurrell <amurrel@purdue.edu> | 2014-04-26 23:38:09 -0400 |
commit | f320bb3bad4f2c3445714f0b45c3a61857203d3f (patch) | |
tree | cd7358553d3aa150bf6741ace17f66972483d328 /lib/throttled_api_request.rb | |
parent | cbdccb99bcad74ffc98f6964fe504e20cfe0cdc2 (diff) | |
parent | 40939795096c0b7a1791d71d920b84ff283fb550 (diff) |
Merge branch 'master' of http://github.com/LukeShu/leaguer
Diffstat (limited to 'lib/throttled_api_request.rb')
-rw-r--r-- | lib/throttled_api_request.rb | 25 |
1 files changed, 25 insertions, 0 deletions
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 |