View Javadoc

1   /*
2    * $Id: HeartbeatAgent.java 20321 2010-11-24 15:21:24Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  package org.mule.example.notifications;
11  
12  import org.mule.AbstractAgent;
13  import org.mule.api.DefaultMuleException;
14  import org.mule.api.MuleException;
15  import org.mule.api.lifecycle.InitialisationException;
16  
17  import javax.resource.spi.work.Work;
18  import javax.resource.spi.work.WorkException;
19  
20  /**
21   * A simple agent that fire {@link org.mule.example.notifications.HeartbeatNotification} events at a given frequency to
22   * notify that the server is alive and well.
23   */
24  public class HeartbeatAgent extends AbstractAgent
25  {
26      public static final String NAME = "Heartbeat";
27  
28      private long frequency = 10000;
29  
30      public HeartbeatAgent()
31      {
32          super(NAME);
33      }
34  
35      public long getFrequency()
36      {
37          return frequency;
38      }
39  
40      public void setFrequency(long frequency)
41      {
42          this.frequency = frequency;
43      }
44  
45      public void initialise() throws InitialisationException
46      {
47          //No Op
48      }
49  
50      public void start() throws MuleException
51      {
52          try
53          {
54              muleContext.getWorkManager().scheduleWork(new Heartbeat());
55          }
56          catch (WorkException e)
57          {
58              throw new DefaultMuleException(e);
59          }
60      }
61  
62      public void stop() throws MuleException
63      {
64          //No Op
65      }
66  
67      public void dispose()
68      {
69          //No Op
70      }
71  
72      public class Heartbeat implements Work
73      {
74          public void release()
75          {
76              //No Op
77          }
78  
79          @SuppressWarnings("synthetic-access")
80          public void run()
81          {
82              while(true)
83              {
84                  muleContext.fireNotification(new HeartbeatNotification(muleContext));
85                  try
86                  {
87                      Thread.sleep(frequency);
88                  }
89                  catch (InterruptedException e)
90                  {
91                      Thread.currentThread().interrupt();
92                      break;
93                  }
94              }
95          }
96      }
97  }