Threads.py

From PeformIQ Upgrade
Revision as of 15:43, 15 February 2008 by PeterHarding (talk | contribs) (New page: <pre> #!/usr/bin/env python #--------------------------------------------------------------------- import time import logging from threading import * from datetime import datetime #---...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
#!/usr/bin/env python

#---------------------------------------------------------------------

import time
import logging

from threading import *
from datetime import datetime

#---------------------------------------------------------------------

LOGFILE = 'threads.log'

#---------------------------------------------------------------------

class my_thread(Thread):
    def __init__(self, target, args=(), name=None):
        # we need a tuple here
        if type(args)<>type((1,)):
            args = (args,)
        Thread.__init__(self, target=target, name=name, args=args)
        self._uptime = datetime.now()
        self.start()

    def getUptime(self):
        return self._uptime

    def __str__(self):
        return self.getName()

#---------------------------------------------------------------------

def get_threads():
    "Does not list main thread..."

    return filter(lambda x: x.getName()<>"MainThread", enumerate())

#---------------------------------------------------------------------

def DoSome(s=""):
   msg = "[DoSome]  %s  Now it's %s" % (s, datetime.now())
   print msg
   log.info(msg)

   time.sleep(0.3)

   for i in range(5):
      msg =  "[DoSome]  %s           %s" % (s, datetime.now())
      print msg
      log.info(msg)
      time.sleep(0.5)

#---------------------------------------------------------------------

if __name__=="__main__":
   #----- Set up logging --------------------------------------------

   log  = logging.getLogger('test')
   hdlr = logging.FileHandler(LOGFILE)
   fmtr = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

   hdlr.setFormatter(fmtr)
   log.addHandler(hdlr) 
   log.setLevel(logging.INFO)

   log.info("[main]  ===== Started processing =====")

   #-----------------------------------------------------------------

   t1 = my_thread(DoSome, ("one"))
   t2 = my_thread(DoSome, ("two"))

   time.sleep(0.7)

   for t in get_threads(): 
      msg = "[main]    %s      %s" % (t, t.getUptime())
      print msg
      log.info(msg)
      time.sleep(0.7)

   #-----------------------------------------------------------------

   log.info("[main]  ===== Finished processing =====")

#---------------------------------------------------------------------