Skip to content

Instantly share code, notes, and snippets.

@emrahgunduz
Created August 18, 2021 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emrahgunduz/b713ef40c26e1cb0ec6eb05d9c12f2b6 to your computer and use it in GitHub Desktop.
Save emrahgunduz/b713ef40c26e1cb0ec6eb05d9c12f2b6 to your computer and use it in GitHub Desktop.
Async timer with callback
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