From bee044629d50766d42ddfb1c8c92ed3267033b14 Mon Sep 17 00:00:00 2001 From: Rapptz Date: Sat, 19 Dec 2015 20:40:06 -0500 Subject: [PATCH] Add background_task example to showcase background tasks. --- examples/background_task.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 examples/background_task.py diff --git a/examples/background_task.py b/examples/background_task.py new file mode 100644 index 000000000..7da6b7b9a --- /dev/null +++ b/examples/background_task.py @@ -0,0 +1,32 @@ +import discord +import asyncio + +client = discord.Client() + +@asyncio.coroutine +def my_background_task(): + yield from client.wait_until_ready() + counter = 0 + channel = discord.Object(id='channel_id_here') + while not client.is_closed: + counter += 1 + yield from client.send_message(channel, counter) + yield from asyncio.sleep(60) # task runs every 60 seconds + +@client.async_event +def on_ready(): + print('Logged in as') + print(client.user.name) + print(client.user.id) + print('------') + +loop = asyncio.get_event_loop() + +try: + loop.create_task(my_background_task()) + loop.run_until_complete(client.login('email', 'password')) + loop.run_until_complete(client.connect()) +except Exception: + loop.run_until_complete(client.close()) +finally: + loop.close()