pgtoolkit/delayedquery.py
changeset 104 d8ff52a0390f
parent 103 24e94a3da209
child 105 10551741f61f
equal deleted inserted replaced
103:24e94a3da209 104:d8ff52a0390f
     1 import threading
       
     2 import time
       
     3 
       
     4 
       
     5 class DelayedQueryThread(threading.Thread):
       
     6     def __init__(self, targetdbm, targetname, delay, query, args):
       
     7         threading.Thread.__init__(self)
       
     8         self.targetdbm = targetdbm
       
     9         self.targetname = targetname
       
    10         self.delay = delay
       
    11         self.query = query
       
    12         self.args = args
       
    13         
       
    14     def run(self):
       
    15         time.sleep(self.delay)
       
    16         with self.targetdbm.cursor(self.targetname) as curs:
       
    17             curs.execute(self.query, self.args)
       
    18 
       
    19 
       
    20 class DelayedQuery:
       
    21     def __init__(self, targetdbm):
       
    22         '''Initialize DelayedQuery.
       
    23         
       
    24         targetdbm -- PgManager-like object
       
    25         
       
    26         '''
       
    27         self.targetdbm = targetdbm
       
    28         self.queryids = set()
       
    29 
       
    30     def add(self, delay, query, args, targetname='default', queryid=None):
       
    31         '''Add query to schedule.
       
    32         
       
    33         delay -- how long to wait, in seconds
       
    34         query, args -- query to be run after delay
       
    35         targetname -- name of connection in PgManager
       
    36         queryid -- discard if query with same id is already scheduled
       
    37         
       
    38         '''
       
    39         if queryid is not None:
       
    40             if queryid in self.queryids:
       
    41                 return
       
    42             self.queryids.add(queryid)
       
    43         
       
    44         t = DelayedQueryThread(self.targetdbm, targetname, delay, query, args)
       
    45         t.start()
       
    46