Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Servlets Code Examples

Background tasks

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
Background tasks package com.ack.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BackgroundTasks extends HttpServlet { private Ticker ticker; public void init() { ticker = new Ticker(); Thread t = new Thread( ticker ); t.start(); } public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { // this servlet processes requests and has a background // thread running to handle the execute of ticker objects // do not pass HttpServletRequest and HttpServletResponse to // background threads res.setContentType( "text/html" ); res.getWriter().println( "check your console, i'm ticking<br>" ); } public void destroy() { ticker.stop(); } } // background task class Ticker implements Runnable { private volatile boolean keepAlive = true; private int count; public synchronized void stop() { keepAlive = false; } public void run() { while( keepAlive ) { System.out.println( "still alive [" + ( count++ ) + "]" ); try { Thread.currentThread().sleep( 5000 ); } catch( InterruptedException ie ) { ie.printStackTrace(); } } } }