2 // ========================================================================
3 // Copyright (c) 1995-2016 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.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.util.thread;
21 import java.util.Timer;
22 import java.util.TimerTask;
23 import java.util.concurrent.RejectedExecutionException;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jetty.util.component.AbstractLifeCycle;
27 import org.eclipse.jetty.util.log.Log;
28 import org.eclipse.jetty.util.log.Logger;
31 /* ------------------------------------------------------------ */
32 /** A scheduler based on the the JVM Timer class
34 public class TimerScheduler extends AbstractLifeCycle implements Scheduler, Runnable
36 private static final Logger LOG = Log.getLogger(TimerScheduler.class);
39 * This class uses the Timer class rather than an ScheduledExecutionService because
40 * it uses the same algorithm internally and the signature is cheaper to use as there are no
41 * Futures involved (which we do not need).
42 * However, Timer is still locking and a concurrent queue would be better.
45 private final String _name;
46 private final boolean _daemon;
49 public TimerScheduler()
54 public TimerScheduler(String name, boolean daemon)
61 protected void doStart() throws Exception
63 _timer = _name == null ? new Timer() : new Timer(_name, _daemon);
69 protected void doStop() throws Exception
77 public Task schedule(final Runnable task, final long delay, final TimeUnit units)
81 throw new RejectedExecutionException("STOPPED: " + this);
82 SimpleTask t = new SimpleTask(task);
83 timer.schedule(t, units.toMillis(delay));
94 schedule(this, 1, TimeUnit.SECONDS);
98 private static class SimpleTask extends TimerTask implements Task
100 private final Runnable _task;
102 private SimpleTask(Runnable runnable)
116 LOG.debug("Exception while executing task " + _task, x);
121 public String toString()
123 return String.format("%s.%s@%x",
124 TimerScheduler.class.getSimpleName(),
125 SimpleTask.class.getSimpleName(),