Need to synchronize a bunch of workers so that only 1 does a particular thing? If yes, then you need a lock file. This package uses a cache store (redis or keydb) to create records atomically that only 1 instance will "own."
$3
This library covers most common use cases for exclusion when working with multiple instances of the same application / container:
* Exclusive initialization: have one of the application instances perform a task on init. * Periodic checks: Have one of the application instances perform a task periodically.
For long running tasks and rare edge cases, it could be possible that the lock is perceived as acquired by more than one instance. This library does not provide strict guarantees for exclusion for tasks that must be processed exactly once in a non-idempotent manner (e.g. appending an item in order processing). Consider using upserts/cas on your persistent DB in those cases or using a dedicated solution for exclusion like etcd / zookeeper.
async function main() { const acquired = await exclusive_lock.acquire() if (acquired) { log.info('You win the race! Lock acquired') } exclusive_lock.release() }
main() `
Auto-refreshing
As a feature, exclusive-lock will start a timer to automatically refresh the TTL on the lock file, as it's assumed that the lock holder will always want to hold the lock until explicitly released. This feature is handled by a setInterval timer and can encouter errors asynchronously. See the error event for details on that.
* The timer is not started until a lock is successfully
acquired. * For clean shutdown, always release() an acquired lock so that the timer is canceled. * refreshed is emitted for every successful refresh.