Help understanding task.create() #684
-
Hi, I'm slowly learning pyscript and really liking it so far. Right now my goal is to make a script that checks if my garage door has been open for 15 minutes and then send me a periodic notification about it until it closes. Thanks to my handy LLM I've gone down the path of trying to create a task that runs at a specific time using: So then I thought I'd explore a simple case to see how I realize I can do this in other ways, but I'm ultimately trying to learn how the Any guidance here?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey @ben-kenney 👋 Tasks are meant for parallel programming eg. when you want to start multiple flows that run all at the same time or separately from the rest of your function - they don't accept any triggers (they just pass the args and kwargs to your function which you provided as the first arg). If you'd like to run your automation with a delay you can make use of the @state_trigger("cover.garage_door == 'open'", state_hold=15 * 60) # garage door must stay open for 15 minutes otherwise function doesn't run
@task_unique("garage_door_notify") # makes sure the function won't trigger again if it's still running (the newly run function will terminate itself)
def notify_about_open_garage():
# I will run when the garage door opens but only if it stays open for 15 minutes
while cover.garage_door == 'open':
my_notify()
task.sleep(15 * 60) # I will block the loop for 15 minutes
# if the door is still open I will re-run the loop sending another notification
# if the door is already closed the function terminates A good scenario for task creation is if you'd like to run multiple things in parallel eg. def my_method():
# will run all slow prints (let's say they take 10 minutes to print the message) at the same time
tasks = [task.create(slow_print, "Hello World!") for slow_print in all_slow_print_methods]
# will wait for all of them to finish
task.wait(set(tasks)) Hope this helps! Let me know if you have questions.
|
Beta Was this translation helpful? Give feedback.
Hey @ben-kenney 👋
Tasks are meant for parallel programming eg. when you want to start multiple flows that run all at the same time or separately from the rest of your function - they don't accept any triggers (they just pass the args and kwargs to your function which you provided as the first arg).
If you'd like to run your automation with a delay you can make use of the
state_trigger
andstate_hold
property (it will only run your function if the condition you put in the string remainsTrue
for the specified amount of time - then it runs):