I have this slackbot that performs a long running task when it receives a message. I want to send an initial “Loading..” message, then if the execution time of the task is taking longer than ~15 seconds, I update the previous message to say “Still loading…”.
I’m not sure how to go about the problem given my program isn’t using the AsyncApp and the only solution I can think of is to use asyncio.wait_for
I’ve tried using asyncio.wait_for(task(), timeout=15)
to update the message, but the update never executes, even if I set the timeout to 1. Also, the long_running_task() function isn’t originally a coroutine, so it isn’t running correctly.
app = App()
async def long_running_task():
...
@app.event("message")
def event_message(client, event, say, logger):
initial_message = say("Loading")
start_message_ts = initial_message["ts"]
async def run_task():
try:
await asyncio.wait_for(long_running_task(), timeout=15)
except asyncio.TimeoutError:
await client.chat_update(
channel=event["channel"],
ts=start_message_ts,
text="Still loading..."
)
asyncio.ensure_future(run_task())
If you want to keep your long task to be a sync (and not async) routine, you can just launch it in a thread, and eventually wait for it :
from threading import Thread
import time
app = App()
def long_running_task():
...
@app.event("message")
def event_message(client, event, say, logger):
initial_message = say("Loading")
start_message_ts = initial_message["ts"]
thread = Thread(target=long_running_task, daemon=True)
thread.start()
started = time.time()
while thread.is_alive():
if time.time()-started>15:
client.chat_update(channel=event["channel"],ts=start_message_ts,text="Still loading...")
break
time.sleep(0.1)#Save CPU
(Here I did not await the client.chat_update
for sake of simplicity, but if needed you would just launch it using asyncio)
3