HRTimer is a simple system-wide timer facility using a singleton Timer, with additional instrumentation.
/**
* Copyright (c) 2006 Richard Rodgers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//package com.monad.homerun.util;
import java.util.Timer;
import java.util.TimerTask;
/**
* HRTimer is a simple system-wide timer facility using a singleton Timer,
* with additional instrumentation.
*/
public class HRTimer
{
// the singleton instance
private static HRTimer instance = null;
// the timer instance
private Timer hrTimer = null;
// task counters
private int numRepeatTasks = 0;
private int numOneOffTasks = 0;
// private constructor
private HRTimer()
{
hrTimer = new Timer( true );
}
/**
* Resturns an instance of an HRTimer
*
* @return timer
* the timer instance
*/
public static synchronized HRTimer getInstance()
{
if ( instance == null )
{
instance = new HRTimer();
}
return instance;
}
/**
* Adds a repeating task to the timer
*
* @param task
* the timer task to add
* @param period
* the time interval between task executions
*/
public void addTask( TimerTask task, long period )
{
++numRepeatTasks;
hrTimer.schedule( task, 0L, period );
}
/**
* Adds a task to be executed only once
*
* @param task
* the task to perform
* @param delay
* initial time interval before execution
*/
public void addOneOffTask( TimerTask task, long delay )
{
++numOneOffTasks;
hrTimer.schedule( task, delay );
}
/**
* Adds a repeating task with an initial delay
*
* @param task
* the task to add
* @param delay
* the intial delay before first execution
* @param period
* the interval between task executions
*/
public void addDelayedTask( TimerTask task, long delay, long period )
{
++numRepeatTasks;
hrTimer.schedule( task, delay, period );
}
/**
* Cancels a regsitered task
*
* @param task
* the task to be cancelled
*/
public void cancelTask( TimerTask task )
{
--numRepeatTasks;
task.cancel();
}
/**
* Returns the number of active tasks
*
* @return num
* the number of current tasks
*/
public int getNumTasks()
{
return numRepeatTasks + numOneOffTasks;
}
/**
* Returns the current number of repeatable tasks
*
* @return num
* the number of repreatable tasks
*/
public int getNumRepeatTasks()
{
return numRepeatTasks;
}
/**
* Returns the current number of non-repeatable tasks
*
* @return num
* the number of non-repreatable tasks
*/
public int getNumOneOffTasks()
{
return numOneOffTasks;
}
}
Related examples in the same category