1 |
torben |
772 |
/* 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 |
torben |
781 |
import java.util.Calendar; |
10 |
|
|
import java.util.Timer; |
11 |
|
|
import java.util.TimerTask; |
12 |
|
|
|
13 |
torben |
772 |
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 |
torben |
781 |
|
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 |
torben |
772 |
|
46 |
torben |
782 |
|
47 |
|
|
|
48 |
torben |
781 |
@Override |
49 |
torben |
782 |
public void destroy() { |
50 |
|
|
super.destroy(); |
51 |
|
|
timer.cancel(); //remove all pending jobs |
52 |
|
|
} |
53 |
|
|
|
54 |
|
|
|
55 |
|
|
|
56 |
|
|
@Override |
57 |
torben |
772 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
58 |
torben |
781 |
//schedule a single run,, run after 3 seconds |
59 |
|
|
//timer.schedule(new MyTask("1"), 3000); |
60 |
|
|
|
61 |
|
|
|
62 |
|
|
//continuous execution first execution after 2 seconds and then with 1 second intervals |
63 |
|
|
//timer.schedule(new MyTask("2"), 2000, 1000); |
64 |
|
|
|
65 |
|
|
//schedule a single run at a specific time |
66 |
|
|
Calendar cal = Calendar.getInstance(); |
67 |
|
|
cal.set(2010, 5, 1, 14, 40, 0); //months are zero indexed |
68 |
|
|
timer.schedule(new MyTask("3"), cal.getTime() ); |
69 |
torben |
782 |
|
70 |
torben |
781 |
response.getWriter().print("ok"); |
71 |
torben |
772 |
} |
72 |
|
|
|
73 |
|
|
} |