In this shorted and simplified code I want to wait for all tasks to be completed( queue.join) and then leave. This code open a network connection and download some data. Unfortunately I have to push 'ctrl-c' because the 'client.run_until_disconnected()'.
The complete code works but I dont'know how to exit without keyboard interruption. I have to schedule it with crontab so I can't use 'client.run_until_disconnected()'
EDIT : updated code
#!/usr/bin/env python3.7
import asyncio
import telethon
from telethon import TelegramClient
from telethon import functions, types
from datetime import datetime
api_id = 00000 # your api_id
api_hash = "your api hash"
async def worker(queue):
while True:
queue_book = await queue.get()
book_name = queue_book.file.name
print(book_name)
loop = asyncio.get_event_loop()
await client.download_media(queue_book,book_name)
queue.task_done()
async def main():
#Free ebook medical articles
channel = await client(functions.messages.CheckChatInviteRequest('your channel hash'))
#values message's id depend on the chosen channel
ids = [63529,63528,63527,63526,63525,63524,63523,63522]
queue = asyncio.Queue(1)
workers = [asyncio.create_task(worker(queue)) for _ in range(5)]
for booksId in ids:
async for get_book in client.iter_messages(channel.chat, ids=booksId):
await queue.put(get_book)
await queue.join()
for the_worker in workers:
the_worker.cancel()
async def wait_until(dt):
now = datetime.now()
await asyncio.sleep((dt - now).total_seconds())
async def run_at(dt, coro):
await wait_until(dt)
return await coro
client = TelegramClient("Test", api_id, api_hash)
loop = asyncio.get_event_loop()
client.start()
try:
loop = loop.create_task(run_at(datetime(2021, 2, 19, 11,00),main()))
client.run_until_disconnected()
except KeyboardInterrupt as keyint:
print("KeyboardInterrupt..")
pass
run_until_disconnected()
is just a helper function, you don't have an obligation to run it if you want to control when the event loop ends. The minimal change would be to replace client.run_until_disconnected()
with loop.run_forever()
, and call loop.stop()
at the end of main()
.
A more idiomatic approach would be to leave main()
as it is, but instead of starting it with create_task
, await it from your top-level coroutine (normally called main
by convention, but you already chose that name for the other function). Then you can just call asyncio.run(actual_main())
, and the program will automatically exit when main
finishes. For example (untested):
# main and other functions as in the question
async def actual_main():
global client
client = TelegramClient("Test", api_id, api_hash)
await client.start()
await run_at(datetime(2021, 2, 19, 11, 00), main())
asyncio.run(actual_main())