[c#]代码库
/// <summary>
/// 定时器
/// </summary>
public class ScheduledControlEngine
{
private Action<DateTime> _action;
private DateTime _lastTime;
private bool _flag;
private int _cycle;
private System.Threading.Thread _mainThread;
/// <summary>
/// 定时器
/// </summary>
/// <param name="firstStartTime">第一次启动基准时间</param>
/// <param name="cycle">在第一次启动时间基础上,执行循环,单位为秒</param>
public ScheduledControlEngine(DateTime firstStartTime, int cycle)
{
_cycle = cycle;
_lastTime = firstStartTime;
_mainThread = new System.Threading.Thread(Loop);
}
public ScheduledControlEngine(DateTime firstStartTime, int cycle, Action<DateTime> action)
{
_cycle = cycle;
_lastTime = firstStartTime;
_mainThread = new System.Threading.Thread(Loop);
RegisterCallback(action);
}
public void RegisterCallback(Action<DateTime> action)
{
_action += action;
}
private void Loop()
{
_flag = true;
while (_flag)
{
var now = DateTime.Now;
if ((now - _lastTime).TotalSeconds > 0)
{
_lastTime = NextTime();
_action(now);
}
System.Threading.Thread.Sleep(1000 * 1);
}
}
private DateTime NextTime()
{
var now = DateTime.Now;
var tsp = now - _lastTime;
var interval = (int)(tsp.TotalSeconds / _cycle);
var nextTime = interval * _cycle;
var time = _lastTime.AddSeconds(nextTime).AddSeconds(_cycle);
return time;
}
public void Start()
{
_mainThread.Start();
}
public void Stop()
{
_flag = false;
}
}
static void Main(string[] args)
{
DateTime firstRunTime;
int cycle=60;
System.Console.WriteLine("系统启动中……");
ScheduledControlEngine controlEngine = new ScheduledControlEngine(firstRunTime, cycle, AutoTrans);
controlEngine.Start();
}
by: 发表于:2017-12-20 17:29:54 顶(0) | 踩(0) 回复
??
回复评论