简体   繁体   English

如何根据时间或特定数量批量处理事件

[英]How to batch process events based on time or after specific amount

I have an event system that I can subscribe to for when a specific object is changed.当特定的 object 发生更改时,我可以订阅一个事件系统。 After receiving this event, I want to execute a task for this object.收到这个事件后,我想为这个object执行一个任务。

It is possible that multiple objects are changed at the same time.有可能同时更改多个对象。 Eg if I change 1000 objects I get 1000 events.例如,如果我更改 1000 个对象,我会得到 1000 个事件。 The problem is that it takes way longer for the task I want to execute to process 1 objects 1000 times than 1000 objects 1 time.问题是我要执行的任务需要更长的时间来处理 1 个对象 1000 次而不是 1000 个对象 1 次。 I cannot change the way the events are generated.我无法更改事件的生成方式。

So what I thought about is to batch up these events when I receive them.所以我想到的是在收到这些事件时将它们批处理。 Eg Collect 1000 Items in a Queue and the execute the task on all objects from the collected events.例如,在队列中收集 1000 个项目,然后对收集到的事件中的所有对象执行任务。 The problem is: what happens when only 999 objects are changed?问题是:当只有 999 个对象被更改时会发生什么? Then my task is never executed.然后我的任务永远不会执行。 So I also want to drain the queue eg 5 seconds after the first object was inserted.所以我还想在插入第一个 object 后 5 秒排空队列。

Is there any library for this specific task?是否有任何用于此特定任务的库? Or do I have to build this myself with a Queue and some logic to do the things I want?还是我必须自己用一个队列和一些逻辑来构建它来做我想做的事情?

I'm almost sure that doesn't exist some specific lib for this, what I done once I needed a same strategy for events like you, was create a queue or a repository to store the events, and started a ScheduledExecutorService with a task running at a fixed rate, to consume the events, if there isn't events to consume I just skiped the execution.我几乎可以肯定不存在一些特定的库,一旦我需要像你这样的事件相同的策略,我所做的就是创建一个队列或存储库来存储事件,并启动一个运行任务的 ScheduledExecutorService以固定速率消耗事件,如果没有要消耗的事件,我只是跳过了执行。 You can even put a verification in the store add method to see if the store has 1000 or more and hasn't been processed yet, so you can fire the task.您甚至可以在 store add 方法中进行验证,以查看 store 是否有 1000 或更多并且尚未处理,因此您可以触发任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM