How to schedule a task in asyncio so it runs at a certain date?
My program is supposed to run 24/7 and i want to be able to run some tasks at a certain hour/date. I have already tried to work with aiocron but it only supports scheduling functions (not coroutine...
stackoverflow.com
import asyncio, datetime
async def wait_until(dt):
# sleep until the specified datetime
now = datetime.datetime.now()
await asyncio.sleep((dt - now).total_seconds())
async def run_at(dt, coro):
await wait_until(dt)
return await coro
async def hello():
print('hello')
loop = asyncio.get_event_loop()
# print hello ten years after this answer was written
loop.create_task(run_at(datetime.datetime(2028, 7, 11, 23, 36),
hello()))
loop.run_forever()
Note: Python versions before 3.8 didn't support sleeping intervals longer than 24 days, so wait_until had to work around the limitation. The original version of this answer defined it like this:
async def wait_until(dt):
# sleep until the specified datetime
while True:
now = datetime.datetime.now()
remaining = (dt - now).total_seconds()
if remaining < 86400:
break
# pre-3.7.1 asyncio doesn't like long sleeps, so don't sleep
# for more than one day at a time
await asyncio.sleep(86400)
'[공부용]참고 사이트 모음 > [python]' 카테고리의 다른 글
[python] datetime.timedelta 를 일, 시간, 분으로 변환 (0) | 2021.05.20 |
---|---|
[python] 파이썬 플라스크 파일 업로드 (0) | 2021.05.18 |
[python] CORS Error 해결법 - Flask 플라스크 예시 (0) | 2021.05.18 |
Python 3, asyncio와 놀아보기 - 스크랩 (0) | 2021.05.16 |
[파이썬] 리눅스에서 디렉토리 퍼미션 (권한) 체크 (0) | 2021.05.04 |