tuya-local icon indicating copy to clipboard operation
tuya-local copied to clipboard

Use entry.async_create_background_task to get HA to manage the task lifecycle

Open make-all opened this issue 1 year ago • 1 comments

From #1917

You may want to consider switching to entry.async_create_background_task (example: https://github.com/home-assistant/core/blob/b84829f70fcd8dfb73cbd9829cf962fc029f0d8e/homeassistant/components/homekit_controller/connection.py#L352) since the task will automatically be cancelled when the config entry is unloaded. https://github.com/home-assistant/core/blob/b84829f70fcd8dfb73cbd9829cf962fc029f0d8e/homeassistant/config_entries.py#L1133

You'll have the pass the config entry to the entity when you create the object.

You can still use hass.async_create_background_task https://github.com/home-assistant/core/blob/2590db1b6dc253e4d80b3fada5b051512be1b21a/homeassistant/core.py#L843 in the mean time if you don't want to refactor. If you use that one instead of entry.async_create_background_task, you'll need make sure the task is cancelled yourself when the entry is unloaded or the entity is removed.

make-all avatar May 15 '24 12:05 make-all

Also, using async_create_background_task instead of async_create_task will allow the task to be started during startup again, and not from EVENT_HOMEASSISTANT_STARTED, since startup does not block on background tasks. This should simplify the code.

make-all avatar May 15 '24 12:05 make-all