JMX 之 TimerService

时间服务在特定的日期和时间触发通知。它能够在常量的时间间隔内重复触发通知,这个通知是通过 timer 发送通知给注册在时间服务上所有对象,这个服务时间是一个 MBean,它能够被管理,允许应用程序配置调度器。
时间服务有2种不同的方式管理通知:

  • 通知只会被触发一次
  • 通知可以在一段间隔时间重复触发

实例
TimerAgent.java

public class TimerAgent {  

    public static void main(String[] args) throws Exception{  
       MBeanServer server = ManagementFactory.getPlatformMBeanServer();  
      ObjectName timerName = new ObjectName("MyTimer:type=MyTimer");  
      Timer timer = new Timer();  

      server.registerMBean(timer, timerName);  
      // 每 1 秒触发  
      Integer nid = timer.addNotification("add", "add time", "hello", new Date(), 1000);  
      server.addNotificationListener(timerName, new NotificationListener() {  
                @Override  
      public void handleNotification(Notification notification, Object handback) {  
                    TimerNotification timerNotification = (TimerNotification) notification;  
                    System.out.println("thread:"+Thread.currentThread().getName()+", "+timerNotification.getNotificationID() + ", " + timerNotification.getType() + ", " + timerNotification.getSource() + ", " + timerNotification.getMessage() + ", " + timerNotification.getUserData()+", "+timerNotification.getSequenceNumber());
                         //执行5次,注销监听器,并且停止服务  
                    if(timerNotification.getSequenceNumber() == 5){  
                        try {  
                            timer.removeNotification(nid);  
                            timer.stop();  
                         } catch (InstanceNotFoundException e) {  
                            e.printStackTrace();  
                          }  
                    }  
                }  
            }, null, null);  
      timer.start();  
  }  
}

output:

thread:Timer-0, 1, add, MyTimer:type=MyTimer, add time, hello, 1
thread:Timer-0, 1, add, MyTimer:type=MyTimer, add time, hello, 2
thread:Timer-0, 1, add, MyTimer:type=MyTimer, add time, hello, 3
thread:Timer-0, 1, add, MyTimer:type=MyTimer, add time, hello, 4
thread:Timer-0, 1, add, MyTimer:type=MyTimer, add time, hello, 5
仅有 1 条评论
  1. 666666666666666666

添加新评论