1 //
2 // ========================================================================
3 // Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
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.TimeUnit;
24
25 import org.eclipse.jetty.util.component.AbstractLifeCycle;
26
27 public class TimerScheduler extends AbstractLifeCycle implements Scheduler
28 {
29 /* this class uses the Timer class rather than an ScheduledExecutionService because
30 * it uses the same algorithm internally and the signature is cheaper to use as there are no
31 * Futures involved (which we do not need).
32 * However, Timer is still locking and a concurrent queue would be better.
33 */
34 Timer _timer;
35 final String _name;
36
37 public TimerScheduler()
38 {
39 this(null);
40 }
41
42 public TimerScheduler(String name)
43 {
44 _name=name;
45 }
46
47 @Override
48 protected void doStart() throws Exception
49 {
50 _timer=_name==null?new Timer():new Timer(_name);
51 super.doStart();
52 }
53
54 @Override
55 protected void doStop() throws Exception
56 {
57 _timer.cancel();
58 super.doStop();
59 _timer=null;
60 }
61
62 @Override
63 public Task schedule(final Runnable task, final long delay, final TimeUnit units)
64 {
65 Timer timer=_timer;
66 if (timer!=null)
67 {
68 SimpleTask t = new SimpleTask(task);
69 _timer.schedule(t,units.toMillis(delay));
70 return t;
71 }
72 throw new IllegalStateException("STOPPED: "+this);
73 }
74
75 private static class SimpleTask extends TimerTask implements Task
76 {
77 private final Runnable _task;
78
79 SimpleTask(Runnable runnable)
80 {
81 _task=runnable;
82 }
83
84 @Override
85 public void run()
86 {
87 _task.run();
88 }
89 }
90
91
92 }