gawel / aiocron

Crontabs for asyncio
MIT License
338 stars 20 forks source link

Unawaited coroutine warning in python 3.9 #26

Open Askaholic opened 2 years ago

Askaholic commented 2 years ago

I've just started running my tests with -W error and sometimes I will see some failures that appear to be caused by this library scheduling a coroutine probably right as the event loop is closing, and then failing to call it.

>               warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))
E               pytest.PytestUnraisableExceptionWarning: Exception ignored in: <coroutine object PlayerService.update_data at 0x7f1b4a266ec0>
E               
E               Traceback (most recent call last):
E                 File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/warnings.py", line 506, in _warn_unawaited_coroutine
E                   warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)
E               RuntimeWarning: coroutine 'PlayerService.update_data' was never awaited

Here's where I create the cron:

    async def initialize(self) -> None:
        await self.update_data()
        self._update_cron = aiocron.crontab(
            "*/10 * * * *", func=self.update_data
        )

I don't call update_data anywhere else in the entire code base except for a single unit test that directly tests the functionality, which passes fine so I know that's not the problem. So I think it must be happening because of this library.

It also seems to happen mostly on GitHub Actions. I don't think I've actually had the tests fail for me locally with this error, which is really annoying because it makes it even harder to debug.

I'm not super familiar with the intricacies of the asyncio event loop call_* functions, but I wonder if there is some way to ensure that the coroutine is either run or not created at all.

Python version: 3.9 Aiocron version: 1.8

gawel commented 2 years ago

Well, you dont know if the coroutine will have to run before the process is closed. I don't see any option to do that.

It may be possible to track initiated coroutines and cancel them on atexit but I really don't like this idea. This kind of hook should not be used in a minimalist library IMHO