--- miscJava/Test3/src/dk/thoerup/schedulesamples/JavaTimer.java 2010/06/01 11:42:06 780 +++ miscJava/Test3/src/dk/thoerup/schedulesamples/JavaTimer.java 2010/06/01 12:41:41 781 @@ -6,6 +6,10 @@ package dk.thoerup.schedulesamples; import java.io.IOException; +import java.util.Calendar; +import java.util.Timer; +import java.util.TimerTask; + import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -16,10 +20,45 @@ */ public class JavaTimer extends HttpServlet { private static final long serialVersionUID = 1L; - - + + class MyTask extends TimerTask { + String str; + int count = 0; + + public MyTask(String s) { + str = s; + } + + @Override + public void run() { + System.out.println("MyTask : " + str); + + count++; + if (count >=10) + this.cancel(); //cancel efter 10 runs + } + + + } + + Timer timer = new Timer(); + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //schedule a single run,, run after 3 seconds + //timer.schedule(new MyTask("1"), 3000); + + + //continuous execution first execution after 2 seconds and then with 1 second intervals + //timer.schedule(new MyTask("2"), 2000, 1000); + + //schedule a single run at a specific time + Calendar cal = Calendar.getInstance(); + cal.set(2010, 5, 1, 14, 40, 0); //months are zero indexed + timer.schedule(new MyTask("3"), cal.getTime() ); + + + response.getWriter().print("ok"); } }