/[projects]/miscJava/Test3/src/dk/thoerup/schedulesamples/JavaTimer.java
ViewVC logotype

Contents of /miscJava/Test3/src/dk/thoerup/schedulesamples/JavaTimer.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 781 - (show annotations) (download)
Tue Jun 1 12:41:41 2010 UTC (13 years, 11 months ago) by torben
File size: 1651 byte(s)
java timer examples
1 /* 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
2 * it executes the scheduled task in a new background thread that the appserver has no control over.
3 *
4 */
5
6 package dk.thoerup.schedulesamples;
7
8 import java.io.IOException;
9 import java.util.Calendar;
10 import java.util.Timer;
11 import java.util.TimerTask;
12
13 import javax.servlet.ServletException;
14 import javax.servlet.http.HttpServlet;
15 import javax.servlet.http.HttpServletRequest;
16 import javax.servlet.http.HttpServletResponse;
17
18 /**
19 * Servlet implementation class JavaTimer
20 */
21 public class JavaTimer extends HttpServlet {
22 private static final long serialVersionUID = 1L;
23
24 class MyTask extends TimerTask {
25 String str;
26 int count = 0;
27
28 public MyTask(String s) {
29 str = s;
30 }
31
32 @Override
33 public void run() {
34 System.out.println("MyTask : " + str);
35
36 count++;
37 if (count >=10)
38 this.cancel(); //cancel efter 10 runs
39 }
40
41
42 }
43
44 Timer timer = new Timer();
45
46 @Override
47 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
48 //schedule a single run,, run after 3 seconds
49 //timer.schedule(new MyTask("1"), 3000);
50
51
52 //continuous execution first execution after 2 seconds and then with 1 second intervals
53 //timer.schedule(new MyTask("2"), 2000, 1000);
54
55 //schedule a single run at a specific time
56 Calendar cal = Calendar.getInstance();
57 cal.set(2010, 5, 1, 14, 40, 0); //months are zero indexed
58 timer.schedule(new MyTask("3"), cal.getTime() );
59
60
61 response.getWriter().print("ok");
62 }
63
64 }

  ViewVC Help
Powered by ViewVC 1.1.20