Python Daemon (multi-thread development)
#! /Usr/bin/pythonimport sys, time, json, loggingimport Queue, threading, datetimefrom lib. base. daemon import Daemonfrom lib. queue. httpsqs. httpsqsClient import HttpsqsClientfrom lib. db. dbMongodb import DbMongodblogging. basicConfig (level = logging. DEBUG, format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ', datefmt = '% a, % d % B % Y % H: % M: % s', filename = 'myapp. log', filemode = 'w') queue = Queue. queue () httpsqs = HttpsqsClient ('2017. 168.0.218 ', '123', 'httpsqs. com ') db = DbMongodb ('2017. 168.0.119 ', 'testdb') class ThreadGetHttpSqs (threading. thread): def _ init _ (self): threading. thread. _ init _ (self) self. httpsqs = httpsqs self. queue = queue def run (self): while True: data = self. httpsqs. get ('logtest') if data is not None: self. queue. put (data) logging.info ('Get: id % s, tablename % s' % (self. getName (), data) else: time. sleep (3) class ThreadInsertDB (threading. thread): def _ init _ (self): threading. thread. _ init _ (self) self. queue = queue self. db = db def run (self): while True: chunk = self. queue. get () s = json. loads (chunk) tablename = s ['table'] data = s ['data'] self. db. save (tablename, data) logging.info ('Insert: id % s, tablename % s' % (self. getName (), tablename) self. queue. task_done () class MyDaemon (Daemon): def _ run (self): while True: for I in range (2): t = ThreadGetHttpSqs () # t. setDaemon (True) t. start () for I in range (2): B = ThreadInsertDB () # t. setDaemon (True) B. start () # The thread is already a permanent loop, and the process cannot recycle time. wait () if _ name _ = "_ main _": daemon = MyDaemon ('/tmp/daemon-example.pid') if len (sys. argv) = 2: if 'Start' = sys. argv [1]: daemon. start () elif 'stop' = sys. argv [1]: daemon. stop () elif 'restart' = sys. argv [1]: daemon. restart () else: print "Unknown command" sys. exit (2) sys. exit (0) else: print "usage: % s start | stop | restart" % sys. argv [0] sys. exit (2)