Timer Wheel
timer-wheel
is a library for JavaScript and TypeScript for efficiently
managing the expiration of a large amount of items. It allows you to schedule
items to be expired after a certain delay and then control when to advance and
handle the expired items.
This implementation is designed for larger delays and has a minimum delay of
1000 ms.
import { TimerWheel } from 'timer-wheel';
const wheel = new TimerWheel<any>();
wheel.schedule('data', 1500 )
setInterval(() => {
const expired = wheel.advance();
for(const data of expired) {
}
}, 1000);
This library is useful for things like expiring caches with lazy expiration,
instead of checking if every cache item should be expired use a wheel to queue
removal actions and call advance
before every get/set. This is how
Transitory implements expiring
caches.
Rescheduling
By default TimerWheel
will schedule the same object to expired more than once.
This will schedule obj
to be expired both after 1 and 5 seconds:
const wheel = new TimerWheel();
const obj = {};
wheel.schedule(obj, 1000);
wheel.schedule(obj, 5000);
If you want to be able to reschedule when an item expires use
ReschedulingTimerWheel
:
import { ReschedulingTimerWheel } from 'timer-wheel';
const wheel = new ReschedulingTimerWheel();
const obj = {};
wheel.schedule(obj, 1000);
wheel.schedule(obj, 5000);
Running actions
There's a wheel designed to run actions available:
import { ActionTimerWheel } from 'timer-wheel';
const wheel = new ActionTimerWheel();
wheel.schedule(() => {
}, 8000);
wheel.advance();