TimeCache
Introduction
This class is a class that stores data to memory. The data is stored with a time to live (TTL) value. When the TTL expires, the data is removed from the cache.
Unlike Singleton TimeCache, this class is not a singleton class.
Examples
This example creates an instance of the TimeCache class with a TTL of 2 seconds.
import time
from ooodev.utils.cache import TimeCache
cache = TimeCache(seconds=2) # 60 seconds
cache["key"] = "value"
assert "key" in cache # True
assert cache["key"] == "value"
time.sleep(1)
assert "key" in cache # True
time.sleep(3)
assert "key" not in cache # True
This example demonstrates the use of the cache_items_expired event. A callback function is called when the TTL expires.
import threading
from ooodev.utils.cache import TimeCache
LOCK = threading.Lock()
def on_items_expired(source, event):
with LOCK:
# event.event_data is a DotDict with an attribute keys
# that contains a list of keys that have expired.
keys = event.event_data.keys
for key in keys:
print(f"Expired: {key}")
cache = TimeCache(60.0) # 60 seconds
cache.subscribe_event("cache_items_expired", on_items_expired)
cache["key"] = "value"
value = cache["key"]
Class
- class ooodev.utils.cache.TimeCache(seconds, cleanup_interval=60.0)[source]
Time based Cache.
Cached items expire after a specified time. If
cleanup_intervalis set, then the cache is cleaned up at regular intervals; Otherwise, the cache is only cleaned up when an item is accessed.Each time an element is accessed, the timestamp is updated. If the element has expired, it is removed from the cache.
When an item expires, the event
cache_items_expiredis triggered. This event is called on a separate thread. for this reason it is important to make sure that the event handler is thread safe. See Also TimeCache- Parameters:
seconds (float) –
cleanup_interval (float) –
- __delitem__(key)[source]
Remove key.
- Parameters:
key (Any) – Any Hashable object.
- Raises:
TypeError – If key is
None.- Return type:
None
Note
Triggers the event
cache_item_removingbefore removing the item. The Event is aCancelEventArgsand can be canceled.Triggers the event
cache_item_removedafter removing the item. The Event is aEventArgs.The event args
event_datais aDotDictinstance that contains the key of the item being removed.- Return type:
None- Parameters:
key (Any) –
- __init__(seconds, cleanup_interval=60.0)[source]
Time based Cache.
- Parameters:
seconds (float) – Cache expiration time in seconds.
cleanup_interval (float, optional) – Cache cleanup interval in seconds. If set to
0then the cleanup is disabled. Defaults to60.0.
- Return type:
None
- __setitem__(key, value)[source]
Set value by key.
- Parameters:
key (Any) – Any Hashable object.
value (Any) – Any object.
- Raises:
TypeError – If key or value is
None.- Return type:
None
Note
Triggers the event
cache_item_addingbefore adding the item. The Event is aCancelEventArgsand can be canceled.Triggers the event
cache_item_addedafter adding the item. The Event is aEventArgs.Triggers the event
cache_item_updatingbefore updating the item. The Event is aCancelEventArgsand can be canceled.Triggers the event
cache_item_updatedafter updating the item. The Event is aEventArgs.The event args
event_datais aDotDictinstance that contains thekey,valueandis_newof the item being added or updated.- Return type:
None- Parameters:
key (Any) –
value (Any) –
- clear_expired()[source]
Clear expired items from the cache.
Note
Triggers the event
cache_items_expired, on a new thread.The event args
event_datais aDotDictinstance that contains thekeysas a list of the items that were removed.- Return type:
None
- get(key)[source]
Get value by key.
- Parameters:
key (Any) – Any Hashable object.
- Returns:
Value or
Noneif not found.- Return type:
Any
Note
The
getmethod is an alias for the__getitem__method. So you can usecache_inst.get(key)orcache_inst[key]interchangeably.
- put(key, value)[source]
Put value by key.
- Parameters:
key (Any) – Any Hashable object.
value (Any) – Any object.
- Return type:
None
Note
The
putmethod is an alias for the__setitem__method. So you can usecache_inst.put(key, value)orcache_inst[key] = valueinterchangeably.- Return type:
None- Parameters:
key (Any) –
value (Any) –
- remove(key)[source]
Remove key.
- Parameters:
key (Any) – Any Hashable object.
- Return type:
None
Note
The
removemethod is an alias for the__delitem__method. So you can usecache_inst.remove(key)ordel cache_inst[key]interchangeably.- Return type:
None- Parameters:
key (Any) –
- start_timer()[source]
Start the timer.
This only applies if the cleanup interval is set.
- Returns:
Trueif the timer is started,Falseif the timer is already running.- Return type:
bool
Note
Triggers the event
time_cache_timer_started.
- stop_timer()[source]
Stop the timer.
This only applies if the cleanup interval is set.
- Returns:
Trueif the timer is stopped,Falseif the timer was not running.- Return type:
bool
Note
Triggers the event
time_cache_timer_stopped.
- property cleanup_interval: float
Gets/Sets Cache cleanup interval in seconds.
- Return type:
float
- property hits: int
Hits count.
- Returns:
Hits count.
- Return type:
int
- property seconds: float
Gets/Sets Cache expiration time in seconds.
- Return type:
float