|
From: Christoph Z. <ci...@on...> - 2007-01-15 14:45:41
|
Salman Toor wrote:
> I still have another question. If we are using commands.getoutput()
> function inside the run() function then how do we handle the
> processes. Because this senario again hangs the Application Server.
I think this is because your thread implicitely (in commands.getoutput)
executes a Python import, while you are currently importing the servlet.
This may create a deadlock with the Webware import magic for servlets.
So you may have to look for a better place to start your servlets. It
depends a bit on what kind of threads you have: Once per page hit, or
continuously? In the former case, just run the threads from the servlet
awake() method. In the latter case, the cleanest solution would be to
start your threads outside the servlet, e.g. in the initialization code
of your Webware context.
Here is an example that creates any number of such background threads
which execute different os commands in different intervals, and a
servlet displaying the result of these commands.
------ Put this in Examples/__init__.py ---------
print "Loading Examples context"
import commands
from threading import Thread, Event
class MyThread(Thread):
def __init__(self, interval, cmd):
Thread.__init__(self)
self.interval = interval
self.cmd = cmd
self.result = None
self.stop_event = Event()
print 'thread <%s> initialized' % self.cmd
def run(self):
print 'thread <%s> startup' % self.cmd
while not self.stop_event.isSet():
self.result = commands.getoutput(self.cmd)
print 'thread <%s>: %s' % (self.cmd, self.result)
self.stop_event.wait(self.interval)
def stop(self):
if self.isAlive():
print 'thread <%s> shutdown' % self.cmd
self.stop_event.set()
self.join(1)
my_threads = None
def contextInitialize(app, ctxPath):
global my_threads
my_threads = [MyThread(1, 'date'), MyThread(3, 'who')]
for t in my_threads:
app.addShutDownHandler(t.stop)
t.start()
------ Put this in Examples/ShowCmd.py ---------
from ExamplePage import ExamplePage
class ShowCmd(ExamplePage):
def writeContent(self):
from Examples import my_threads
self.write('<h1>Thread Test</h1>')
for t in my_threads:
self.write('<h2>Thread "%s"</h2>' % t.cmd)
self.write('<pre>%s</pre>' % t.result)
---------------------------------------------------
Now you can watch the results on http://localhost:8080/ShowCmd.
-- Christoph
|