Python method to run the specified function every n seconds

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.