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 |
@Resource |
27 |
private SessionContext sessionCtx; |
28 |
int count; |
29 |
|
30 |
public void startTimer() { |
31 |
|
32 |
TimerService timerService = sessionCtx.getTimerService(); |
33 |
|
34 |
|
35 |
//Timer timer = timerService.createTimer( (5 * 1000), null); //singleshot timer |
36 |
timerService.createTimer(10*1000, 5000, null); //repeating timer |
37 |
|
38 |
// otherwise use schedule expression to create more complex schedules |
39 |
// in this case fire once every minute when the seconds is == 10 |
40 |
//ScheduleExpression se = new ScheduleExpression().second(10).minute("*").hour("*"); |
41 |
//System.out.println(se.toString()); |
42 |
//timerService.createCalendarTimer( se ); |
43 |
|
44 |
count = 0; |
45 |
} |
46 |
|
47 |
@Override |
48 |
public void ejbTimeout(Timer timer) { |
49 |
|
50 |
count++; |
51 |
|
52 |
System.out.print("timeout .... " + count); |
53 |
|
54 |
|
55 |
if (count >= 10) { |
56 |
timer.cancel(); |
57 |
} |
58 |
} |
59 |
|
60 |
} |