delay a task until certain time

后端 未结 8 1951
梦谈多话
梦谈多话 2021-01-11 11:59

What I want to do in a python script is sleep a number of seconds until the required time is reached. IE: if runAt setting is 15:20 and current time is 10:20, how can I wor

8条回答
  •  被撕碎了的回忆
    2021-01-11 12:18

    If you subtract one datetime object from another you get a timedelta object, which has a seconds property, so you can do:

    t1 = datetime.datetime.now()
    
    # other stuff here
    t2 = datetime.datetime.now()
    delta = t2 - t1
    if delta.seconds > WAIT:
        # do stuff
    else:
        # sleep for a bit
    

    As an aside, you might want to use cron for tasks that are supposed to run at specific times.

提交回复
热议问题