8.1. Describe timer services
Timer services is a service of scheduling notifications in the bean container.
(Available for all bean types except from stateful session beans).
Timers services can be created
-Programmatically, using TimerService interface
-By annotations @Schedule
Functionality that a bean with timer services can perform:
- Create a timer notification callback
- Process a timer notification callback
- Manage timer objects (list notification, cancel timer etc...)
The timers can be classified as:
- Single notifications
- Interval (multiple notifications at specified interval)
- Calendar based schedule
- second, minute, hour
- dayOfWeek, dayOfMonth
- month
- year
- Expressions : wildcard (*), list(,), range(-),intervals(/)
8.2. Create a timer notification callback
- By timerService interface
- Single:
- Calendar based: using javax.ejb.ScheduleExpression
schedule.dayOfMonth("1,Last");//first and last day of the month
Timer timer = timerService.createCalendarTimer(schedule);
When a timer expires the container calls the bean's method annotated with @Timeout (*Note: this method must return void and the argument is optional).
- By annotation
Example : @Schedule(dayOfWeek="Mon", hour="0")
8.3. Process a timer notification callback
Example with timerService interface
To execute this bean we need to make a call from a client (for example a servlet class) to the method setTimer that indicates the milliseconds after the timeout will happen: scheduleBean.setTimer(30000);
Results in server console:
2016-03-26T11:58:33.313+0000|Info: TestBean was successfully deployed in 362 milliseconds.
2016-03-26T12:00:26.816+0000|Info: the next timeout is programed Sat Mar 26 12:00:56 GMT 2016 happening in 29968 milliseconds
2016-03-26T12:00:56.787+0000|Info: Timeout occurred
Example with schedule annotation
The following example is a stateless session bean, with a timer scheduled every 1 min.
When it is deployed in the server, after 1 minute the timeout method is called:
Results in server console:
2016-03-26T10:03:00.001+0000|Info: Automatic timeout occured
2016-03-26T10:04:00.002+0000|Info: Automatic timeout occured
2016-03-26T10:05:00.001+0000|Info: Automatic timeout occured
2016-03-26T10:06:00.002+0000|Info: Automatic timeout occured
2016-03-26T10:07:00.002+0000|Info: Automatic timeout occured
8.4. Manage timer objects
-Cancel() - cancel a timer
-getHandle() - obtain a serializable object
-getTimeRemaining()
-getNextTimeout()
-getInfo()
When using container-managed transactions @Timeout can use attributes: Required or RequiredNew to preserve transaction integrity, which means that in case of rollback the timeout will be reset.
OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification
No comments:
Post a Comment