Python Loop timer service function (similar to contrab)

Source: Internet
Author: User
Tags posix

The Loop Timer service functionality implemented by Python is similar to the Contrab functionality under Linux. Mainly through the timer implementation.

Note: Threading.timer in Python is thread-based, and each time a timed event is generated, the thread ends after the callback response function is completed. The threads in Python cannot be restart, so this looping timer must be restarted after each scheduled response is complete and then another timed event.

#!/usr/bin/env python#-*-coding:utf-8-*-#import subprocessfrom Threading Import timerimport timeimport osimport sysif Os.name = = ' POSIX ': def become_daemon (our_home_dir= '. ', out_log= '/dev/null ', err_log= '/dev/null ',        umask=0o022): "Robustly turn to a UNIX daemon, running in Our_home_dir." # First Fork Try:if os.fork () > 0:sys.exit (0) # kill off parent except OS        Error as E:sys.stderr.write ("Fork #1 failed: (%d)%s\n"% (E.errno, e.strerror)) Sys.exit (1)  Os.setsid () Os.chdir (Our_home_dir) Os.umask (umask) # Second fork Try:if Os.fork () > 0:os._exit (0) except OSError as E:sys.stderr.write ("Fork #2 failed: (%d)%s\n"%            (E.errno, E.strerror))        Os._exit (1) si = open ('/dev/null ', ' r ') so = open (Out_log, ' A + ', 0) se = open (err_log, ' A + ', 0) Os.dup2 (Si.fileno (),Sys.stdin.fileno ()) os.dup2 (So.fileno (), Sys.stdout.fileno ()) os.dup2 (Se.fileno (), Sys.stderr.fileno ())        # Set Custom file descriptors so this they get proper buffering.        Sys.stdout, Sys.stderr = So, seelse:def Become_daemon (our_home_dir= '. ', Out_log=none, Err_log=none, umask=0o022): "" "If we ' re not running under a POSIX system, just simulate the daemon mode by doing redirections and Di        Rectory changing. "" "Os.chdir (Our_home_dir) os.umask (umask) sys.stdin.close () sys.stdout.close () sys.std Err.close () If Err_log:sys.stderr = open (Err_log, ' a ', 0) Else:sys.stderr = Nulldevi    CE () If out_log:sys.stdout = open (Out_log, ' a ', 0) else:sys.stdout = Nulldevice ()        Class Nulldevice: "A writeable object, writes to nowhere--like/dev/null."   Def write (self, s): Passdef OutputLog (sLog): Print SLog def tolog (sLog): Sinfo = Time.strftime ("%y%m%d%h:%m:%s") Sinfo + = SLog OutputLog (sinfo) def log_info (SLog): t Olog (' info\t ' + sLog) def log_error (SLog): Tolog (' error\t ' + sLog) def log_debug (SLog): Tolog (' debug\t ' + sLog Class Timerrunner: "' Ntimescds = 2 #时间间隔 scmd = ' Calc ' oTm = None @classmethod def become Daemonize (CLS): Become_daemon () @classmethod def runcmd (CLS): Osubpcs = subprocess. Popen (Cls.scmd, stdout=subprocess. PIPE, stderr = subprocess. PIPE) While True:nreturncode = Osubpcs.poll () if 0 = = Nreturncode:log_info (o SubPcs.stdout.read ()) break elif 0 > Nreturncode:log_error (oSubPcs.stderr.rea D ()) Break @classmethod def Timerfun (CLS): Log_info ("Go-to-timer fun") cls. Inittimer () Cls.oTm.start () #再次启动计时, placed before the Runcmd function, guarantees the accuracy of the time CLS. Runcmd () Log_info ("Exit Timer Fun ") @classmethod def Inittimer (CLS): Cls.otm = Timer (Cls.ntimescds, Cls.timerfun) @classmethod def Run (CLS): Cls.inittimer () Cls.timerfun () cls.becomedaemonize () de F Main (): Timerrunner.run ()


Python Loop timer service function (similar to contrab)

Related Article

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.