pgtoolkit/delayedquery.py
author Radek Brich <radek.brich@devl.cz>
Tue, 19 Mar 2013 16:46:36 +0100
changeset 79 d02a36d0a9b0
parent 18 a9e12b7cc207
permissions -rw-r--r--
Update PgManager doc.

import threading
import time


class DelayedQueryThread(threading.Thread):
    def __init__(self, targetdbm, targetname, delay, query, args):
        threading.Thread.__init__(self)
        self.targetdbm = targetdbm
        self.targetname = targetname
        self.delay = delay
        self.query = query
        self.args = args
        
    def run(self):
        time.sleep(self.delay)
        with self.targetdbm.cursor(self.targetname) as curs:
            curs.execute(self.query, self.args)


class DelayedQuery:
    def __init__(self, targetdbm):
        '''Initialize DelayedQuery.
        
        targetdbm -- PgManager-like object
        
        '''
        self.targetdbm = targetdbm
        self.queryids = set()

    def add(self, delay, query, args, targetname='default', queryid=None):
        '''Add query to schedule.
        
        delay -- how long to wait, in seconds
        query, args -- query to be run after delay
        targetname -- name of connection in PgManager
        queryid -- discard if query with same id is already scheduled
        
        '''
        if queryid is not None:
            if queryid in self.queryids:
                return
            self.queryids.add(queryid)
        
        t = DelayedQueryThread(self.targetdbm, targetname, delay, query, args)
        t.start()