Reputation: 1019
i want to run my function and then I want to find now's time using python.
then lets say after 2 hours my function should run again.
what should i do?
Upvotes: 0
Views: 207
Reputation: 3626
import datetime
import time
def func():
# your function
pass
while True:
func() # call you function
print datetime.datetime.now() # print current datetime
time.sleep(2*60*60) # sleep for 2 hours
However, a better way for a scheduled operation would be to use cron
, as @Silver Light suggested.
Upvotes: 1
Reputation: 45902
to determine current time, you can use pythons datetime module
from datetime import datetime
print datetime.datetime.now();
To run script every two hours - this is a job to crontab deamon. This is a special process in UNIX systems that executed commands in periods of time.
Read about setting up cron jobs here: http://blog.dreamhosters.com/kbase/index.cgi?area=2506
Upvotes: 2
Reputation: 7997
Is your process going to be running for hours at a time and doing other things? If so you can mark the time like so:
from time import time
start_time = time() # current time expressed as seconds since 1/1/1970
...
now = time()
if (now - start_time) >= (2 * 60 * 60): # number of seconds in 2 hours
do_function()
Otherwise, if it will not need to do anything for 2 hours, you can do:
from time import sleep
quit_condition = False
if not quit_condition:
sleep(2 * 60 * 60) # control will not return to this thread for 2 hours
quit_condition = do_function()
In the second scenario, presumably your function will indicate whether or not the main loop can be exited.
Upvotes: 0
Reputation: 80011
There are several ways of finding the time in Python:
import time
print time.time() # unix timestamp, seconds from 1970
import datetime
print datetime.datetime.now()
time.sleep(7200) # sleep for 2 hours
Upvotes: 2