1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.util.thread;
20
21 import java.util.Timer;
22 import java.util.TimerTask;
23 import java.util.concurrent.RejectedExecutionException;
24 import java.util.concurrent.TimeUnit;
25
26 import org.eclipse.jetty.util.component.AbstractLifeCycle;
27 import org.eclipse.jetty.util.log.Log;
28 import org.eclipse.jetty.util.log.Logger;
29
30 public class TimerScheduler extends AbstractLifeCycle implements Scheduler
31 {
32 private static final Logger LOG = Log.getLogger(TimerScheduler.class);
33
34
35
36
37
38
39
40
41 private final String _name;
42 private Timer _timer;
43
44 public TimerScheduler()
45 {
46 this(null);
47 }
48
49 public TimerScheduler(String name)
50 {
51 _name=name;
52 }
53
54 @Override
55 protected void doStart() throws Exception
56 {
57 _timer=_name==null?new Timer():new Timer(_name);
58 super.doStart();
59 }
60
61 @Override
62 protected void doStop() throws Exception
63 {
64 _timer.cancel();
65 super.doStop();
66 _timer=null;
67 }
68
69 @Override
70 public Task schedule(final Runnable task, final long delay, final TimeUnit units)
71 {
72 Timer timer=_timer;
73 if (timer==null)
74 throw new RejectedExecutionException("STOPPED: "+this);
75 SimpleTask t = new SimpleTask(task);
76 timer.schedule(t,units.toMillis(delay));
77 return t;
78 }
79
80 private static class SimpleTask extends TimerTask implements Task
81 {
82 private final Runnable _task;
83
84 private SimpleTask(Runnable runnable)
85 {
86 _task=runnable;
87 }
88
89 @Override
90 public void run()
91 {
92 try
93 {
94 _task.run();
95 }
96 catch (Throwable x)
97 {
98 LOG.debug("Exception while executing task "+_task,x);
99 }
100 }
101
102 @Override
103 public String toString()
104 {
105 return String.format("%s.%s@%x",
106 TimerScheduler.class.getSimpleName(),
107 SimpleTask.class.getSimpleName(),
108 hashCode());
109 }
110 }
111 }