001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.servicemix.timers.impl;
018
019 import java.util.Date;
020 import java.util.TimerTask;
021
022 import org.apache.commons.logging.Log;
023 import org.apache.commons.logging.LogFactory;
024 import org.apache.servicemix.timers.Timer;
025 import org.apache.servicemix.timers.TimerListener;
026 import org.apache.servicemix.timers.TimerManager;
027
028 public class TimerManagerImpl implements TimerManager {
029
030 private static final Log LOG = LogFactory.getLog(TimerManagerImpl.class);
031
032 private java.util.Timer timer;
033
034 public Timer schedule(TimerListener listener, long delay) {
035 if (LOG.isDebugEnabled()) {
036 LOG.debug("Schedule timer " + listener + " for " + delay);
037 }
038 TimerImpl tt = new TimerImpl(listener);
039 timer.schedule(tt, delay);
040 return tt;
041 }
042
043 public Timer schedule(TimerListener listener, Date date) {
044 if (LOG.isDebugEnabled()) {
045 LOG.debug("Schedule timer " + listener + " at " + date);
046 }
047 TimerImpl tt = new TimerImpl(listener);
048 timer.schedule(tt, date);
049 return tt;
050 }
051
052 public void start() {
053 timer = new java.util.Timer();
054 }
055
056 public void stop() {
057 timer.cancel();
058 }
059
060 protected static class TimerImpl extends TimerTask implements Timer {
061
062 private TimerListener timerListener;
063
064 public TimerImpl(TimerListener timerListener) {
065 this.timerListener = timerListener;
066 }
067
068 public boolean cancel() {
069 if (LOG.isDebugEnabled()) {
070 LOG.debug("Timer " + timerListener + " cancelled");
071 }
072 return super.cancel();
073 }
074
075 public TimerListener getTimerListener() {
076 return this.timerListener;
077 }
078
079 public void run() {
080 if (LOG.isDebugEnabled()) {
081 LOG.debug("Timer " + timerListener + " expired");
082 }
083 this.timerListener.timerExpired(this);
084 }
085
086 }
087
088 }