using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Api.Framework.SDK
{
///
/// 定时器
///
public abstract class TimerTask : IDisposable
{
///
/// 是否在运行
///
public new bool IsRunning { get; protected set; }
///
/// 运行的数量
///
public new long RunningCount { get; set; }
///
/// 执行任务
///
public new void ExecutionTask(object state, bool timedOut)
{
if (IsRunning) return;
try
{
IsRunning = true;
RunningCount++;
this.Run(state, timedOut);
}
catch (Exception ex)
{
EventClient.OnEvent(this, $"ERROR.:{this.GetType()}-{System.Reflection.MethodBase.GetCurrentMethod().Name}-->{ex.Message},{ex.StackTrace}");
}
finally
{
IsRunning = false;
}
}
///
/// 运行主体 - 需要重写
///
public abstract void Run(object state, bool timedOut);
///
/// 销毁方法 - 可以被重写
///
public new virtual void Dispose() { this.IsRunning = false; }
///
/// RegisterdHandler
///
public new RegisteredWaitHandle RegisterdHandler { get; private set; }
///
/// WaitHandler
///
public new WaitHandle WaitHandler { get; private set; }
static TimerTask() { Timers = new Dictionary(); }
private static Dictionary Timers { get; set; }
///
/// 获得定时器
///
public static TimerTask GetTimer()
{
var type = typeof(T);
if (Timers.ContainsKey(type)) return Timers[type];
return null;
}
public static T NewTimer(T task, int second, object state = null)
{
var _t = task as TimerTask;
if (_t == null) throw new Exception($"不支持{typeof(T)}类型,请继承[Api.Framework.TimerClient]!");
Close();
var type = task.GetType();
_t.WaitHandler = new AutoResetEvent(false);
_t.RegisterdHandler = ThreadPool.RegisterWaitForSingleObject(_t.WaitHandler, new WaitOrTimerCallback(_t.ExecutionTask), state, second * 1000, false);
Timers[type] = _t;
return task;
}
///
/// 创建一个定时器
///
///
public static T NewTimer(int second, object state = null)
{
if (second == 0) second = 1;
var time = System.Activator.CreateInstance();
var _t = time as TimerTask;
if (_t == null) throw new Exception($"不支持{typeof(T)}类型,请继承[Api.Framework.TimerClient]!");
Close();
var type = time.GetType();
_t.WaitHandler = new AutoResetEvent(false);
_t.RegisterdHandler = ThreadPool.RegisterWaitForSingleObject(_t.WaitHandler, new WaitOrTimerCallback(_t.ExecutionTask), state, second * 1000, false);
Timers[type] = _t;
return time;
}
///
/// 关闭一个定时器
///
public static new void Close()
{
var type = typeof(T);
if (Timers.ContainsKey(type))
{
var t = Timers[type];
Timers.Remove(type);
if (t != null && t.WaitHandler != null && t.RegisterdHandler != null)
{
t.RegisterdHandler.Unregister(t.WaitHandler);
t.Dispose();
}
}
}
protected bool IsStart
{
get
{
if (this.WaitHandler != null && this.RegisterdHandler != null) return true;
return false;
}
}
}
}