This example describes how Python runs the specified function every n seconds. Share to everyone for your reference. Specific as follows:
This is a timer-like effect, every specified number of seconds to run the specified function, using thread implementation, code simple and practical.
Copy the 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 (%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)
Hopefully this article will help you with Python programming.