This article describes how to run a specified function in python every N seconds. it involves Python's thread and time operation skills and is very useful, for more information about how to run a specified function every N seconds, see the example in this article. Share it with you for your reference. The details are as follows:
This is similar to the timer effect. it runs the specified function every specified number of seconds and is implemented in a thread. the code is simple and practical.
The code is 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 t Exception, e:
Print e
If _ name __= = "_ main __":
Interval = 5
Command = r "ipconfig"
Run (interval, command)
I hope this article will help you with Python programming.