> ## Documentation Index
> Fetch the complete documentation index at: https://rasa.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom timer store

> Write a session timer store that keeps timers in your own backend, or change the built-in Redis timer store.

A timer store holds session timers. A session timer tracks whether a conversation
is still active. Mantle schedules one when a session starts, resets it after each
user message, and fires it when the session has had no user message for
[`session_expiration_time`](https://rasa.com/docs/mantle/reference/agent-yml#session_config) minutes. Without
a `timer_store:` section, timers stay in memory. Write your own store when your
backend is none of the built-in ones, or subclass the Redis store to change how
it behaves.

## Before you start

Put your code in a package next to `agent.yml`: a folder named `addons/` with an
empty `__init__.py` file. Start `rasa` from the project root so the package can
be imported.

## Subclass `SessionTimerStore`

Import `SessionTimerStore` and `SessionTimer` from `rasa.api.timers.v1`, and
implement every method in the table below.

```python addons/custom_timer_store.py theme={null}
import time
from typing import Any, Optional

from rasa.api.timers.v1 import SessionTimer, SessionTimerStore, TimerStoreSettings


class MyTimerStore(SessionTimerStore):
    def __init__(self) -> None:
        super().__init__()
        self.timers: dict[str, SessionTimer] = {}

    def connect(self, settings: TimerStoreSettings) -> None:
        self.endpoint = settings.params["endpoint"]

    def close(self) -> None:
        """Release the connection when the timer manager stops."""
        self.timers.clear()

    async def store_timer(
        self,
        sender_id: str,
        session_id: Optional[str],
        scheduled_time: float,
        metadata: Optional[dict[str, Any]] = None,
    ) -> None:
        """Save a timer for a conversation, replacing any earlier timer for it.

        The timer manager calls this when it schedules or resets a session timer.
        """
        self.timers[sender_id] = SessionTimer.create_timer(
            sender_id, session_id, scheduled_time, metadata
        )

    async def delete_timer(
        self,
        sender_id: str,
        only_if_scheduled_time: Optional[float] = None,
    ) -> bool:
        """Remove the timer for a conversation and return True if one was removed.

        When only_if_scheduled_time is set, remove the timer only if its time still
        matches. The manager uses this so one worker claims each expired timer.
        """
        timer = self.timers.get(sender_id)
        if timer is None:
            return False
        if (
            only_if_scheduled_time is not None
            and timer.scheduled_time != only_if_scheduled_time
        ):
            return False
        del self.timers[sender_id]
        return True

    async def get_timer(self, sender_id: str) -> Optional[SessionTimer]:
        """Return the timer for a conversation, or None if it has none."""
        return self.timers.get(sender_id)

    async def get_expired_timers(
        self, cutoff_time: Optional[float] = None
    ) -> list[SessionTimer]:
        """Return timers whose scheduled time is at or before cutoff_time, or now if None.

        The timer manager polls this to find timers to fire.
        """
        cutoff = time.time() if cutoff_time is None else cutoff_time
        return [
            timer for timer in self.timers.values() if timer.scheduled_time <= cutoff
        ]
```

This example keeps timers in a dictionary so you can run it as written. Replace
the dictionary calls with calls to your backend to share timers between
processes. Keep the method signatures.

| Method | Required | Purpose |
| - | - | - |
| `connect(settings)` | yes | Open your connection, using `settings.params` |
| `close()` | yes | Release the connection and any state held in memory |
| `store_timer(sender_id, session_id, scheduled_time, metadata)` | yes | Save a timer for a conversation, replacing any earlier one |
| `delete_timer(sender_id, only_if_scheduled_time)` | yes | Remove the timer. When `only_if_scheduled_time` is set, remove it only if its time matches. Return whether a timer was removed |
| `get_timer(sender_id)` | yes | Return the timer for a conversation, or `None` |
| `get_expired_timers(cutoff_time)` | yes | Return timers whose `scheduled_time` is at or before `cutoff_time`. `None` means now |

Register the class under `timer_store`:

```yaml integrations.yml theme={null}
timer_store:
  type: addons.custom_timer_store.MyTimerStore
  endpoint: ${TIMER_STORE_ENDPOINT}
```

A custom timer store runs with the persistent timer manager. The `redis`
built-in runs with the Redis timer manager instead. `poll_interval` still sets how
often Mantle checks for expired timers.

## Subclass the built-in Redis store

To change one behavior of the `redis` store and keep the rest, subclass
`RedisSessionTimerStore`. This example adds a `team` field to the metadata of
every timer:

```python addons/custom_redis_timer_store.py theme={null}
from typing import Any, Optional

from rasa.api.timers.v1 import RedisSessionTimerStore


class MyRedisTimerStore(RedisSessionTimerStore):
    async def store_timer(
        self,
        sender_id: str,
        session_id: Optional[str],
        scheduled_time: float,
        metadata: Optional[dict[str, Any]] = None,
    ) -> None:
        """Tag each timer with the team, then save it with the built-in Redis store."""
        tagged = {**(metadata or {}), "team": "support"}
        await super().store_timer(sender_id, session_id, scheduled_time, tagged)
```

```yaml integrations.yml theme={null}
timer_store:
  type: addons.custom_redis_timer_store.MyRedisTimerStore
  host: ${REDIS_HOST}
  port: 6379
  db: 2
  password: ${REDIS_PASSWORD}
  poll_interval: 1.0
```

The Redis keys in [`timer_store`](https://rasa.com/docs/mantle/reference/integrations-yml#timer_store) apply
to your subclass. Keep `type` set to the class path, because the built-in name
`redis` selects the built-in class.

## Versioning

The import `rasa.api.timers.v1` is the version. YAML names only the class. See
[Custom integrations: Versioning](https://rasa.com/docs/mantle/reference/custom-integrations.md#versioning).


## Related topics

- [Timer Stores](https://rasa.com/docs/reference/integrations/timer-stores.md)
- [Custom integrations](https://rasa.com/docs/mantle/reference/custom-integrations.md)
- [integrations.yml](https://rasa.com/docs/mantle/reference/integrations-yml.md)
- [Mantle Changelog](https://rasa.com/docs/mantle/changelog.md)
- [Custom knowledge store](https://rasa.com/docs/mantle/reference/custom-knowledge-store.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.