diff options
author | nfoy <nfoy@purdue.edu> | 2014-04-26 23:45:25 -0400 |
---|---|---|
committer | nfoy <nfoy@purdue.edu> | 2014-04-26 23:45:25 -0400 |
commit | 6f19b51f0adf95b1d9bd8317388ecdbcb3756be7 (patch) | |
tree | c4be583ba9db126ef58db7a1900468ec0929df25 /lib/throttled_api_request.rb | |
parent | 9d8d6b023ce3390f3ccf9808e630505a15ebebe6 (diff) | |
parent | 9dd899559e4533c61089c3f9429574d2de20925e (diff) |
Merge branch 'master' of https://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 |