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