6 |
package dk.thoerup.schedulesamples; |
package dk.thoerup.schedulesamples; |
7 |
|
|
8 |
import java.io.IOException; |
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; |
import javax.servlet.ServletException; |
14 |
import javax.servlet.http.HttpServlet; |
import javax.servlet.http.HttpServlet; |
15 |
import javax.servlet.http.HttpServletRequest; |
import javax.servlet.http.HttpServletRequest; |
20 |
*/ |
*/ |
21 |
public class JavaTimer extends HttpServlet { |
public class JavaTimer extends HttpServlet { |
22 |
private static final long serialVersionUID = 1L; |
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 { |
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 |
} |
} |