控制ExecutorService最多每秒执行N个任务 [英] Control ExecutorService to execute N tasks per second maximum

查看:576
本文介绍了控制ExecutorService最多每秒执行N个任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何控制/限制提交到 ExecutorService ?我有 SMSTask 发送短信,我需要控制执行器,以便它最多只能发送N条消息/秒。

How to control/limit the tasks that are submitted to a ExecutorService? I have SMSTask that sends SMS messages and I need to control the executor so that it can only send at maximum N messages/second.

推荐答案

假设您正在为每个任务创建一条短信,您可以使用ScheduleExecutorService。

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);

将任务添加到队列中,它们将以每秒10个的速度进行处理。

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

这篇关于控制ExecutorService最多每秒执行N个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆