|
From: Christoph Z. <ci...@on...> - 2007-01-13 18:52:41
|
Salman Toor wrote:
> What is the proper way of using multi threaded application within WebKit.
>
> for example:
>
> # define a class that subclasses Thread
> class showTime(threading.Thread):
>
> # define instance constructor
> def __init__(self,interval,id):
> self.w = interval
> self.id = id
> threading.Thread.__init__(self) # we are required to this
>
> # define run method (body of the thread)
> def run(self):
> time.sleep(self.w)
> print "thread", self.id, "done at", time.ctime(time.time())
>
> how do i start the threads so that it can finish successfully and i
> can shutdown my server and can restart it.
Hi Salman,
here is a simple example servlet. The thread is started when the servlet
is first called and stopped when the AppServer stops.
---------------------------------------------------------------
from ExamplePage import ExamplePage
from time import *
from threading import Thread, Event
class MyThread(Thread):
def __init__(self, interval, id):
Thread.__init__(self)
self.interval = interval
self.id = id
self.time = None
self.stop_event = Event()
def run(self):
while not self.stop_event.isSet():
self.time = ctime(time())
print "thread", self.id, "done at", self.time
self.stop_event.wait(self.interval)
def stop(self):
print "thread", self.id, "shutdown"
self.stop_event.set()
self.join(1)
my_thread = MyThread(2, 4711)
from WebKit.AppServer import globalAppServer
globalAppServer.application().addShutDownHandler(my_thread.stop)
my_thread.start()
class ShowTime(ExamplePage):
def writeContent(self):
self.write('<h1>Thread Test</h1>')
self.write('<h2>Last executed at: ', my_thread.time, '</h2>')
---------------------------------------------------------------
Hope that helps.
-- Christoph
|