Write your thread class (myThreadClass) as implementing Runnable.  

Write a class that implements ServletContextListener and config it in
web.xml like this:

        <listener>
                <listener-class>mypackage.MyScListenerClass</listener-class>
        </listener>

Now have your ServletContextListener start a new thread using your Runnable
class in its contextInitialized method, which is called when the app starts.

You might want to consider what happens if/when the run() method of your
myThreadClass returns.  Do you want to restart the thread again or not?  If
yes, you might need to put it in a while loop within run() - if this is of
the type while(true) until it throws an exception, make sure that you catch
the Exception gracefully, and also include code like this in the innermost
part of the loop so that it is well-behaved about sharing resources with
other threads on the machine:

   Thread.currentThread().sleep(1000 * delayMilliseconds);

You might also think about what needs to be done to gracefully exit from the
thread when TC shuts down.  This will influence whether you make the thread
daemon or not, and whether you need inter-thread communication so that your
main webapp can tell your non-daemon thread to exit gracefully ASAP.

Have used this approach before, and am about to use same approach again on
another project.  It works.  You *do* need to take care about being
threadsafe.  If you don't understand how to do that, then you need to read
up on it - it's beyond the scope of a single email.

You can find more detail on all the stuff above in the javadocs, or reply to
the list if you have any specific Qs and I'll try to pick it up.

> -----Original Message-----
> From: Terence Chan [mailto:[EMAIL PROTECTED] 
> Sent: Wednesday 25 May 2005 11:24
> To: 'Tomcat Users List'
> Subject: How to create user thread in tomcat
> 
> 
> Hi,
> 
> Please help. I would like to create a thread or service that 
> start running
> once the web server is started. This thread need to 
> communicate with other
> applications using HTTP protocol.
> 
> Terence  
> 
> -- 
> Internal Virus Database is out-of-date.
> Checked by AVG Anti-Virus.
> Version: 7.0.308 / Virus Database: 266.11.8 - Release Date: 5/10/2005
>  
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> 
> 



---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to