sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.
https://sanic.dev
MIT License
18k stars 1.54k forks source link

Hot reloads don't pause background tasks #2693

Closed David-xian66 closed 1 year ago

David-xian66 commented 1 year ago

Is there an existing issue for this?

Is your feature request related to a problem? Please describe.

Hot reloads don't pause background tasks

tittle(Chinese):热重载不会暂停后台任务

Describe the solution you'd like

I've created a custom background task to start a single job thread (which will loop indefinitely), this thread will not be paused after sanic hot reload when I change the code, and I want to create a custom function for developers to define what needs to be done before hot reload

Chinese:我自定义了一个后台任务,用来启动一个单独作业的线程(这个线程会进行无限循环),当我更改代码,sanic热重载后,这个线程不会被暂停,我希望能自定义一个函数,用于开发者自定义在热重载前需要执行的操作

my code:

async def Start():
    overview_Thread = threading.Thread(target=overview_Thread_Main, args=(JSON))
    overview_Thread.start()

app.add_task(Start())

Additional context

No response

Tronic commented 1 year ago

Your task terminates instantly (with Start function returning) but the thread keeps running in background without Sanic knowing of it. Consider using asyncio run_in_executor instead so that you can await for the result and that Sanic may cancel the awaited call, which causes an exception in the thread and for it to terminate.

Please ask support questions like this on the forums, or use an AI like ChatGPT, https://you.com/chat or Bing chat for immediate answers (also in Chinese).

David-xian66 commented 1 year ago

Your task terminates instantly (with Start function returning) but the thread keeps running in background without Sanic knowing of it. Consider using asyncio run_in_executor instead so that you can await for the result and that Sanic may cancel the awaited call, which causes an exception in the thread and for it to terminate.

Please ask support questions like this on the forums, or use an AI like ChatGPT, https://you.com/chat or Bing chat for immediate answers (also in Chinese).

So, how do I wait for the thread to finish asynchronously,🤔

David-xian66 commented 1 year ago

I don't know how to use asyncio to start threading🤔(And also allow sanic to close the thread itself)

David-xian66 commented 1 year ago

I'm using a while True loop for threads

David-xian66 commented 1 year ago

I'm using a while True loop for threads

Or…, how can I fix the asynchrony effect of while True🤔

ahopkins commented 1 year ago

This issue has been mentioned on Sanic Community Discussion. There might be relevant details there:

https://community.sanicframework.org/t/hot-reloads-dont-pause-background-tasks/1156/1