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.activemq.thread;
018
019 import java.util.HashMap;
020 import java.util.Timer;
021 import java.util.TimerTask;
022
023 import org.apache.activemq.util.ServiceStopper;
024 import org.apache.activemq.util.ServiceSupport;
025
026 /**
027 *
028 */
029 public final class Scheduler extends ServiceSupport {
030 private final String name;
031 private Timer timer;
032 private final HashMap<Runnable, TimerTask> timerTasks = new HashMap<Runnable, TimerTask>();
033
034 public Scheduler (String name) {
035 this.name = name;
036 }
037
038 public void executePeriodically(final Runnable task, long period) {
039 TimerTask timerTask = new SchedulerTimerTask(task);
040 timer.schedule(timerTask, period, period);
041 timerTasks.put(task, timerTask);
042 }
043
044 /*
045 * execute on rough schedule based on termination of last execution. There is no
046 * compensation (two runs in quick succession) for delays
047 */
048 public synchronized void schedualPeriodically(final Runnable task, long period) {
049 TimerTask timerTask = new SchedulerTimerTask(task);
050 timer.schedule(timerTask, period, period);
051 timerTasks.put(task, timerTask);
052 }
053
054 public synchronized void cancel(Runnable task) {
055 TimerTask ticket = timerTasks.remove(task);
056 if (ticket != null) {
057 ticket.cancel();
058 timer.purge(); // remove cancelled TimerTasks
059 }
060 }
061
062 public synchronized void executeAfterDelay(final Runnable task, long redeliveryDelay) {
063 TimerTask timerTask = new SchedulerTimerTask(task);
064 timer.schedule(timerTask, redeliveryDelay);
065 }
066
067 public void shutdown() {
068 timer.cancel();
069 }
070
071 @Override
072 protected synchronized void doStart() throws Exception {
073 this.timer = new Timer(name, true);
074 }
075
076 @Override
077 protected synchronized void doStop(ServiceStopper stopper) throws Exception {
078 if (this.timer != null) {
079 this.timer.cancel();
080 }
081 }
082
083 public String getName() {
084 return name;
085 }
086 }