public class TimerTaskManger
{
private readonly Dictionary<string, TimerTask> AllTimerMangerDic = new Dictionary<string, TimerTask>();
public bool RegistTimer(string name, Action<object> action, int interval)
{
return RegistTimer(name, action, interval, 0);
}
public bool RegistTimer(string name, Action<object> action, int interval, int delayMillisecond)
{
return RegistTimer(name, action, null, interval, delayMillisecond);
}
public bool RegistTimer(string name, Action<object> action, object obj, int interval, int delayMillisecond)
{
if (string.IsNullOrEmpty(name) || action == null || this.AllTimerMangerDic.ContainsKey(name))
{
return false;
}
lock (AllTimerMangerDic)
{
AllTimerMangerDic.Add(name, new TimerTask(name, action, obj, interval, delayMillisecond));
}
return true;
}
public bool UnRegistTimer(string name)
{
lock (AllTimerMangerDic)
{
if (AllTimerMangerDic.ContainsKey(name))
{
var timerTask = AllTimerMangerDic[name];
if (timerTask.IsRun)
{
timerTask.Stop();
}
AllTimerMangerDic.Remove(name);
return true;
}
}
return false;
}
public bool SetTaskTimerEnabled(string name, bool flag)
{
lock (AllTimerMangerDic)
{
if (!AllTimerMangerDic.ContainsKey(name))
{
return false;
}
var timerTask = AllTimerMangerDic[name];
if (flag)
{
if (!timerTask.IsRun)
{
timerTask.ResetStart();
}
}
else
{
timerTask.Stop();
}
}
return true;
}
}
public class TimerTask
{
public readonly string TimerName;
private Action<object> InvokeMethod;
private object stateObj;
private int interval;
public int Interval
{
get { return interval; }
set
{
if (value > 0)
{
this.interval = value;
}
}
}
private int delayMillisecond;
public int DelayMillisecond
{
get { return delayMillisecond; }
set
{
if (value > 0)
{
this.delayMillisecond = value;
}
}
}
private System.Threading.Timer threadTimer = null;
public bool IsRun { get; private set; }
public TimerTask(string timerName, Action<object> entrust, object obj, int timeInterval, int delayTime)
{
if (entrust == null)
{
throw new ArgumentNullException("entrust");
}
this.stateObj = obj;
this.TimerName = timerName;
this.InvokeMethod = entrust;
this.interval = timeInterval;
this.delayMillisecond = delayTime;
threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(this.InvokeMethod), this.stateObj, this.delayMillisecond, this.interval);
this.IsRun = true;
}
public bool Stop()
{
if (threadTimer != null)
{
threadTimer.Dispose();
}
this.IsRun = false;
return true;
}
public bool ResetStart()
{
if (threadTimer != null)
{
threadTimer.Dispose();
}
threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(this.InvokeMethod), this.stateObj, this.delayMillisecond, this.interval);
this.IsRun = true;
return true;
}
}
后期在做更改