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