Timing and scheduling.
Hi,
I need to schedule jobs, and don't want to use Quartz, I would rather use the standard JMX timing service. I don't seem to be able to find any good documentation with nice examples that I can adopt.
I have some vanilla code that registers a Timer object with the MBean server, then you add some notification listeners and the listener will get all the notifications that are present in the server at that time. Problem with this is that each listener gets all the notifications.
I don't need this functionality, I need each listener to get different notifications, i.e. listener 1 gets notified every second, and listener 2 gets notified three times once per minute then gets removed from the listeners map.
Does anyone have a tutorial that I can have a look at, or better yet some snippet that I can modify to suit?
Thanks in advance.
Mike
Mike,
I can see a couple of ways to achieve what you want. The first is to create one Timer MBean per job, and have each listener listen to the appropriate MBean. The second is to use a NotificationFilter for each listener that selects only the notifications it is interested in. That might look something like this:
<pre>
public class TimerNotificationFilter implements NotificationFilter {
public TimerNotificationFilter(Integer id) {
this.id = id;
}
public boolean isNotificationEnabled(Notification n) {
if (!(n instanceof TimerNotification))
return false;
TimerNotification tn = (TimerNotification) n;
return (id.equals(tn.getNotificationId()));
}
private final Integer id;
}
</pre>
Then you can arrange for your listener <code>myListener</code> to be called every five seconds with code like this:
<pre>
TimerMBean timer = (TimerMBean)
MBeanServerInvocationHandler.newProxyInstance(
mbeanServer, timerObjectName, TimerMBean.class, true);
Integer id = timer.addNotification("type", "message", null, new Date(), 5000L);
NotificationFilter filter = new TimerNotificationFilter(id);
NotificationBroadcaster timerBroadcaster = (NotificationBroadcaster) timer;
timerBroadcaster.addNotificationListener(myListener, filter, null);
</pre>