Created
August 18, 2021 09:21
-
-
Save emrahgunduz/b713ef40c26e1cb0ec6eb05d9c12f2b6 to your computer and use it in GitHub Desktop.
Async timer with callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from asyncio import Future | |
from collections import Callable | |
from typing import ClassVar | |
from typing import Optional | |
class Timer: | |
_task: Optional[ Future ] = None | |
_timeout: ClassVar[ float ] | |
_callback: ClassVar[ Callable ] | |
def __init__ ( self, timeout, callback ): | |
self._timeout = timeout | |
self._callback = callback | |
async def _job ( self ): | |
await asyncio.sleep( self._timeout ) | |
await self._callback() | |
def start ( self ): | |
self._task = asyncio.ensure_future( self._job() ) | |
def cancel ( self ): | |
if self._task is not None: | |
self._task.cancel() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment