KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > TimerResource


1 package example;
2
3 import java.util.Timer JavaDoc;
4 import java.util.TimerTask JavaDoc;
5
6 import java.util.logging.Logger JavaDoc;
7
8 import javax.resource.spi.ResourceAdapter JavaDoc;
9 import javax.resource.spi.ResourceAdapterInternalException JavaDoc;
10 import javax.resource.spi.BootstrapContext JavaDoc;
11
12 import javax.resource.spi.work.Work JavaDoc;
13 import javax.resource.spi.work.WorkManager JavaDoc;
14 import javax.resource.spi.work.WorkException JavaDoc;
15
16 import com.caucho.jca.AbstractResourceAdapter;
17
18 import com.caucho.config.types.Period;
19
20 /**
21  * Implements a resource which uses uses Work management for
22  * separate threading.
23  */

24 public class TimerResource extends AbstractResourceAdapter {
25   private static final Logger JavaDoc log =
26     Logger.getLogger(TimerResource.class.getName());
27
28   // The initial delay of the task.
29
private long _initialDelay = 0;
30   
31   // The period of the task
32
private long _period = 10000L;
33   
34   // The count of times the server has looped
35
private int _count;
36
37   private Timer JavaDoc _timer;
38
39   /**
40    * Sets the initial delay using the Resin-specific period notation:
41    * 10s, 10m, etc.
42    */

43   public void setInitialDelay(Period initialDelay)
44   {
45     _initialDelay = initialDelay.getPeriod();
46   }
47
48   /**
49    * Sets the period using the Resin-specific period notation:
50    * 10s, 10m, etc.
51    */

52   public void setPeriod(Period period)
53   {
54     _period = period.getPeriod();
55   }
56   
57   /**
58    * Adds to the count.
59    */

60   public void addCount()
61   {
62     _count++;
63   }
64   
65   /**
66    * The start method is called when the resource adapter starts, i.e.
67    * when the web-app or host initializes.
68    */

69   public void start(BootstrapContext JavaDoc ctx)
70     throws ResourceAdapterInternalException JavaDoc
71   {
72     log.info("WorkResource[] starting");
73
74     WorkManager JavaDoc workManager = ctx.getWorkManager();
75     
76     Work JavaDoc work = new WorkTask(this);
77
78     TimerTask JavaDoc timerTask = new WorkScheduleTimerTask(workManager, work);
79
80     _timer = ctx.createTimer();
81
82     _timer.schedule(timerTask, _initialDelay, _period);
83   }
84   
85   /**
86    * Called when the resource adapter is stopped, i.e. when the
87    * web-app or host closes down.
88    */

89   public void stop()
90     throws ResourceAdapterInternalException JavaDoc
91   {
92     log.info("Resource[" + _count + "] stopping");
93
94     _timer.cancel();
95   }
96
97   /**
98    * Returns a printable version of the resource.
99    */

100   public String JavaDoc toString()
101   {
102     return "WorkResource[" + _count + "]";
103   }
104 }
105
Popular Tags