Python------Daemon Implementation

Source: Internet
Author: User

The previous Python------Daemon Daemon learned the implementation of the Python daemon class, a class timereminder that implements a time-alert inheritance Daemon.

Timer class:

#!/usr/bin/env python#-*-coding:utf-8-*-Import TimeImportThreadingclassTimer (Threading. Thread):"""very simple but useless timer. """          def __init__(self, seconds): Self.runtime=seconds Threading. Thread.__init__(self)defRun (self): Time.sleep (self.runtime)Print "buzzzz!! Time ' s up!"    classCountdowntimer (Timer):"""a timer that can counts down the seconds. """          defRun (self): counter=Self.runtime forSecinchRange (Self.runtime): Time.sleep (1.0) Counter-= 1classcountdownexec (countdowntimer):"""A timer that, execute an action at the end of the timer run. """          def __init__(Self, seconds, action, args=[]): Self.args=args self.action=action Countdowntimer.__init__(self, seconds)defRun (self): Countdowntimer.run (self) self.action (Self.args)defMyaction (args=[]):          Print "performing my action with args:"          Printargsif __name__=="__main__": T= Countdownexec (3, Myaction, ["Hello"," World"]) T.start ()
View Code

Message Reminder Script:

#!/usr/bin/env pythonImportThreadingImport TimeImportSysid=0classListener (Threading. Thread):def __init__(self,strs=()): Threading. Thread.__init__(self) self.strs=STRsdefRun (self):GlobalID while  not(IDinchself.strs): Input= Raw_input ('Need to has a free time now! (y|n) \ n') ID=Inputlisten= Listener (('y','Y') ) Listen.setdaemon (True) Listen.start () counter=10 while  not(IDinch('y','Y')): Time.sleep (1)    Print('need to hava a free time now! (y|n)')     ifIdinch('N','N'): Counter= 30#RemindCounter = counter-1ifCounter <0:id='y'
View Code

Reminder Class (Timereminder):

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSys,time,subprocess,os fromMod_daemonImportDaemon fromMod_timerImportcountdownexecclassTimereminder (Daemon):def __init__(Self,limittime,pidfile,stderr,stdout,stdin): Daemon.__init__(Self,pidfile,stderr,stdout,stdin) self.limittime=LimittimedefLogout (SELF,STR): LogFile= Open (Self.stdout,'a') CurrentTime=Time.asctime (Time.localtime (Time.time ())) Logfile.write ("begin%s at%s \ n"%(Str,currenttime)) Logfile.flush () logfile.close ()defRun (self): Self.logout ('Start This program')         whileTrue:t= Countdownexec (self.limittime,presentresult,["Hello"," World"]) T.start () T.join () self.logout ('remind to relax')defPresentresult (args=[]): cmd="xterm-e./sandbox/py_time_reminder/out.py"  #present ReminderChild=subprocess. Popen (cmd,shell=True) child.wait ()defgetlimittime ():Try: Pros= Open ('/sandbox/py_time_reminder/pros.ini','R') Timepro=Int (Pros.read (). Strip ()) Pros.close ()except: Sys.exit ('must set time property first')    ifTimepro:returnTimeproElse:        returnint' -')defSetlimittime (Tim): Pros= Open ('/sandbox/py_time_reminder/pros.ini','W') Pros.write ("%s\n"%Tim) Pros.close ()if __name__=="__main__":    ifLen (SYS.ARGV) <2: Sys.exit ('No action specified.')    Else:        ifSys.argv[1].startswith ('--'): Option= Sys.argv[1][2:]            ifoption = ='Limit'  andLen (sys.argv) = = 3: Mytimelimit= Sys.argv[2] Setlimittime (mytimelimit)elifoption = ='version':                Print " "Version:1.1author:victor" "            elifoption = =' Help':                Print " "This program was to remind to has a free time after set-time work.option includes:--help:display this Help --limit:set [TIME] (s) to remind--version:diaplay version Detailsusage Includes:start:program star T stop:program stop Restart:program Restart" "            Else:                Print 'unkown option.'sys.exit (0)elifLen (sys.argv) = = 2: Ltime=getlimittime () daemon= Timereminder (Ltime,'/sandbox/py_time_reminder/daemon.pid', stderr='/sandbox/py_time_reminder/daemonerr.log', stdout='/sandbox/py_time_reminder/daemonout.log', stdin='/dev/null')            if 'Start'= = Sys.argv[1]: Daemon.start ()elif 'Stop'= = Sys.argv[1]: daemon.stop ()elif 'Restart'= = Sys.argv[1]: Daemon.restart ()Else:                Print("unkown Command") sys.exit (0)Else:                    Print("Usage:%s--help"%sys.argv[0]) sys.exit (2)
View Code

Python------Daemon Implementation

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.