1 |
package dk.thoerup.schedulesamples; |
2 |
|
3 |
import java.io.Serializable; |
4 |
|
5 |
import java.util.Calendar; |
6 |
import java.util.Date; |
7 |
|
8 |
import javax.annotation.Resource; |
9 |
import javax.ejb.ScheduleExpression; |
10 |
import javax.ejb.SessionContext; |
11 |
import javax.ejb.Stateless; |
12 |
import javax.ejb.TimedObject; |
13 |
import javax.ejb.Timeout; |
14 |
import javax.ejb.Timer; |
15 |
import javax.ejb.TimerService; |
16 |
|
17 |
/* GFv3: before using a timed bean make sure the ejb timer service is correctly configured with a datasource and the timer table is created |
18 |
* cd <glassfishv3>/glassfish/domains/domain1/lib/databases/ejbtimer |
19 |
* /usr/lib/jvm/java-6-sun/db/bin/ij |
20 |
* connect 'jdbc:derby:.'; |
21 |
* paste content from <glassfishv3>/glassfish/lib/install/databases/ejbtimer_derby.sql |
22 |
* and content from <glassfishv3>/glassfish/lib/install/databases/upgrade/ejbtimer_upgrade_derby.sql (need the applicationID column) |
23 |
* after this make sure that all the files are owned by the user your GFv3 instance is running as |
24 |
* */ |
25 |
|
26 |
@Stateless |
27 |
public class TimedEjb /*implements TimedObject*/ { |
28 |
|
29 |
public static class TimerInfo implements Serializable { |
30 |
static final long serialVersionUID = 1L; |
31 |
|
32 |
private long start = System.currentTimeMillis(); |
33 |
|
34 |
public long getStart() { |
35 |
return start; |
36 |
} |
37 |
|
38 |
} |
39 |
|
40 |
private int count; //storing shared data like this is not recommended !!! |
41 |
|
42 |
@Resource |
43 |
private SessionContext sessionCtx; |
44 |
|
45 |
public void startTimer() { |
46 |
|
47 |
TimerService timerService = sessionCtx.getTimerService(); |
48 |
|
49 |
TimerInfo info = new TimerInfo(); //the info object is not necessary - but can be used to store data with the timer |
50 |
|
51 |
//Timer timer = timerService.createTimer( (5 * 1000), info); //singleshot timer |
52 |
timerService.createTimer(10*1000, 5000, info ); //repeating timer |
53 |
|
54 |
// otherwise use schedule expression to create more complex schedules |
55 |
// in this case fire once every minute when the seconds is == 10 |
56 |
//ScheduleExpression se = new ScheduleExpression().second(10).minute("*").hour("*"); |
57 |
//System.out.println(se.toString()); |
58 |
//timerService.createCalendarTimer( se ); |
59 |
|
60 |
count = 0; |
61 |
|
62 |
} |
63 |
|
64 |
//@Override if we used TimedObject interface |
65 |
//public void ejbTimeout(Timer timer) { |
66 |
|
67 |
//@Timeout |
68 |
public void myEjbTimeout(Timer timer) { |
69 |
|
70 |
TimerInfo info = (TimerInfo) timer.getInfo(); |
71 |
|
72 |
//any updates to the info object is not pushed back to the timer services |
73 |
|
74 |
System.out.print("timeout .... " + count + " / " + info.getStart() ); |
75 |
count++; |
76 |
|
77 |
if (count >= 10) { |
78 |
timer.cancel(); |
79 |
} |
80 |
} |
81 |
|
82 |
} |