Cache.add()
Store value only if key is missing or expired.
Usage
Cache.add(
key,
value,
expire=None,
)Atomic across threads and processes: when several callers race to add one key, exactly one succeeds. That makes it a simple way to claim a job or take a lock.
Parameters
key: str-
The key.
value: Any-
The value, as for set().
expire: float | None = None- Seconds until the entry expires, or None for never.
Returns
bool-
True if the value was stored, False if the key already held a live value. With
returns True, so use a non-durable handle for claims and locks.durable=True, also False if the write failed, so a claim fails closed. A NullCache
Raises
Examples
if cache.add('job:hourly-cleanup', os.getpid(), expire=55 * 60):
remove_stale_sessions() # only the worker whose add() returned True gets here