Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delay a task until certain time

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 work out how many seconds to sleep? I'm not sure how to convert 15:20 to a time and current date then deduct the actual time to get the seconds.

like image 898
Martlark Avatar asked Jul 05 '11 07:07

Martlark


3 Answers

Think you can also use the following code:

from datetime import datetime, time
from time import sleep

def act(x):
    return x+10

def wait_start(runTime, action):
    startTime = time(*(map(int, runTime.split(':'))))
    while startTime > datetime.today().time(): # you can add here any additional variable to break loop if necessary
        sleep(1)# you can change 1 sec interval to any other
    return action

wait_start('15:20', lambda: act(100))
like image 113
Artsiom Rudzenka Avatar answered Oct 23 '22 19:10

Artsiom Rudzenka


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.

like image 43
Mikesname Avatar answered Oct 23 '22 17:10

Mikesname


You could instead use the pause package ( https://pypi.python.org/pypi/pause ). Taking an example from their documentation -

import pause, datetime
dt = datetime.datetime(2013, 6, 2, 14, 36, 34, 383752)
pause.until(dt)
like image 6
cmangla Avatar answered Oct 23 '22 17:10

cmangla