Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Allow modules to schedule delayed background calls. #15993

Merged
merged 5 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/15993.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow modules to schedule delayed background calls.
37 changes: 37 additions & 0 deletions synapse/module_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from typing_extensions import ParamSpec

from twisted.internet import defer
from twisted.internet.interfaces import IDelayedCall
from twisted.web.resource import Resource

from synapse.api import errors
Expand Down Expand Up @@ -1230,6 +1231,42 @@ def looping_background_call(
f,
)

def delayed_background_call(
self,
msec: float,
f: Callable,
clokep marked this conversation as resolved.
Show resolved Hide resolved
*args: object,
desc: Optional[str] = None,
**kwargs: object,
) -> IDelayedCall:
"""Wraps a function as a background process and calls it in a given number of milliseconds.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth mentioning that if the service is restarted then the task won't run?


Added in Synapse v1.89.0.

Args:
msec: How long to wait before calling, in milliseconds.
f: The function to call once. f can be either synchronous or
asynchronous, and must follow Synapse's logcontext rules.
More info about logcontexts is available at
https://matrix-org.github.io/synapse/latest/log_contexts.html
*args: Positional arguments to pass to function.
desc: The background task's description. Default to the function's name.
**kwargs: Keyword arguments to pass to function.

Returns:
IDelayedCall handle from twisted, which allows to cancel the delayed call if desired.
"""

if desc is None:
desc = f.__name__

return self._clock.call_later(
msec * 0.001,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For my own reference: call_later seems to take a delay in seconds, so this converts milliseconds to seconds.

run_as_background_process,
desc,
lambda: maybe_awaitable(f(*args, **kwargs)),
)

async def sleep(self, seconds: float) -> None:
"""Sleeps for the given number of seconds.

Expand Down
Loading