Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Carlos Wu
Added: Jan 29, 2018 9:38 AM
Views: 11
Tags: no tags
限制一段時間內服務次數
  1. package com.ctbclife.service;
  2.  
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ScheduledExecutorService;
  5. import java.util.concurrent.Semaphore;
  6. import java.util.concurrent.TimeUnit;
  7.  
  8. /**
  9.  * 負責限制打Fitbit的次數
  10.  * User: Carlos
  11.  * Date: 2018/1/29
  12.  */
  13. public class SimpleRateLimiter {
  14.  
  15.     private Semaphore semaphore;
  16.     private int maxPermits;
  17.     private TimeUnit timePeriod;
  18.     private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  19.  
  20.     public static SimpleRateLimiter create(int permits, TimeUnit timePeriod) {
  21.         return new SimpleRateLimiter(permits, timePeriod);
  22.     }
  23.  
  24.     private SimpleRateLimiter(int permits, TimeUnit timePeriod) {
  25.         this.semaphore = new Semaphore(permits);
  26.         this.maxPermits = permits;
  27.         this.timePeriod = timePeriod;
  28.     }
  29.  
  30.     public boolean tryAcquire() {
  31.         if (semaphore.availablePermits() == maxPermits) {
  32.             schedulePermitReplenishment();
  33.         }
  34.         return semaphore.tryAcquire();
  35.     }
  36.  
  37.     public void stop() {
  38.         scheduler.shutdownNow();
  39.     }
  40.  
  41.     private void schedulePermitReplenishment() {
  42.         scheduler.schedule(new Runnable() {
  43.             @Override
  44.             public void run() {
  45.                 semaphore.release(maxPermits - semaphore.availablePermits());
  46.             }
  47.         }, 1, timePeriod);
  48.     }
  49. }
  50.