This example describes how Python runs the specified function every n seconds. Share to everyone for your reference. Specifically as follows:
This is a timer-like effect, each specified number of seconds to run the specified function, using a thread implementation, the code is simple and practical.
Copy Code code as follows:
Import OS
Import time
def print_ts (message):
print ' [%s]%s '% (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()), message)
def run (interval, command):
Print_ts ("-" *100)
Print_ts ("Command%s"%command)
Print_ts ("Starting every%s seconds." %interval)
Print_ts ("-" *100)
While True:
Try
# Sleep for the remaining seconds of interval
time_remaining = Interval-time.time ()%interval
Print_ts ("Sleeping until%s seconds) ..." ((Time.ctime (Time.time () +time_remaining)), time_remaining)
Time.sleep (time_remaining)
Print_ts ("starting command.")
# Execute the command
Status = Os.system (command)
Print_ts ("-" *100)
Print_ts ("Command status =%s.") %status)
Except Exception, E:
Print E
If __name__== "__main__":
Interval = 5
Command = r "ipconfig"
Run (interval, command)
I hope this article will help you with your Python programming.