Welcome, guest | Sign In | My Account | Store | Cart

The Timer class was originally written to be used in conjuction with a Progress Bar and a custom driver function. Three example functions are given in discussion to help better illustrate how this can be used.

Python, 38 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import thread
import time

################################################################################

class Timer:

    # Create Timer Object
    def __init__(self, interval, function, *args, **kwargs):
        self.__lock = thread.allocate_lock()
        self.__interval = interval
        self.__function = function
        self.__args = args
        self.__kwargs = kwargs
        self.__loop = False
        self.__alive = False

    # Start Timer Object
    def start(self):
        self.__lock.acquire()
        if not self.__alive:
            self.__loop = True
            self.__alive = True
            thread.start_new_thread(self.__run, ())
        self.__lock.release()

    # Stop Timer Object
    def stop(self):
        self.__lock.acquire()
        self.__loop = False
        self.__lock.release()

    # Private Thread Function
    def __run(self):
        while self.__loop:
            self.__function(*self.__args, **self.__kwargs)
            time.sleep(self.__interval)
        self.__alive = False
def start_progress_bar(share):
    PB_object = progress_bar.PB(400, 40)
    Timer_object = timer.Timer(1, update_progress_bar, PB_object, share)
    share.append(Timer_object)
    Timer_object.start()
    return PB_object, Timer_object

def stop_progress_bar(PB_object, Timer_object):
    Timer_object.stop()
    PB_object.close()

def update_progress_bar(PB_object, share):
    try:
        PB_object.update(share[0] / share[1])
    except:
        share[2].stop()

The share variable was originally defined [float(), len(old_string)], and share[0] was updated each time through the processing loop.

2 comments

yunusnsubuga 11 years, 5 months ago  # | flag

How do i get this to run? In other words, i'm new to python and i would like so see how this thing works. Thanks.

Stephen Chappell (author) 11 years, 5 months ago  # | flag

This is a class/module that you can use in your programs. An instance of the class can run a function at regular interval in a separate thread. That means the rest of your program can do other things simultaneously as the timer is running.