Control ExecutorService to execute N tasks per second maximum

梦想的初衷 提交于 2019-12-02 19:47:43

Assuming you are creating one SMS message per task you can use a ScheduleExecutorService.

final Queue<Task> tasks = new ConcurrentLinkedQueue<Task>();
int ratePerSecond = 10;
final ExecutorService es = Executors.newCachedThreadPool();
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        final Task task = tasks.poll();
        if (task == null) return;
        es.submit(new Runnable() {
            @Override
            public void run() {
                process(task);
            }
        });
    }
}, 0, 1000/ratePerSecond, TimeUnit.MILLISECONDS);

Add tasks to the queue and they will be processed at a rate of 10 per second.

Try RateLimiter from Guava. You must share one instance between all tasks running in the pool:

final RateLimiter rateLimiter = RateLimiter.create(N)

//and in your task:

rateLimiter.tryAcquire();
sendSms();

tryAcquire(); will block for the amount of time precisely to preserve N frequency.

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!