/* using java.util.timer is the most simple but also very inflexible - and It is considered less-than-nice in relation to the app server since * it executes the scheduled task in a new background thread that the appserver has no control over. * */ 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; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class JavaTimer */ 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"); } }