using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Linq; using NetLibrary.Log; namespace NetLibrary { public class TimeTask { public List ListModel = new List(); private AutoResetEvent AutoReset = new AutoResetEvent(false); bool IsRun = false; TaskModel cTask = null; //当前任务 #region 启动任务 public void Start() { cTask = null; if (ListModel.Count == 0) return; Thread t1 = new Thread(new ThreadStart(this.OnStart)); t1.Name = "定时任务"; t1.Start(); } #endregion #region 停止任务 public void Stop() { IsRun = false; AutoReset.Set(); } #endregion #region 计算下一个任务 public void MathNextTask() { if (cTask != null) { if (cTask.Interval == 0) { ListModel.Remove(cTask); if (ListModel.Count == 0) { cTask = null; Stop(); return; } if (ListModel.Count == 1) cTask = ListModel[0]; return; } else { cTask.NextTime = cTask.NextTime.AddMinutes(cTask.Interval); } //ErrorFollow.TraceWrite("下次执行任务时间", "", cTask.NextTime.ToString("yyyy-MM-dd HH:mm:00")); } if (ListModel.Count == 1) { if (cTask==null) cTask = ListModel[0]; return; } var query = from item in ListModel orderby item.NextTime ascending select item; cTask = query.First(); //foreach (TaskModel item in ListModel) //{ // if (cTask == null) { cTask = item; } // else // { // if (item.NextTime < cTask.NextTime) cTask = item; // } //} } #endregion #region 睡眠 public void WaitOne() { if (cTask == null) return; if (cTask.NextTime0) AutoReset.WaitOne(ts, false); } #endregion #region 执行任务 void OnStart() { IsRun = true; MathNextTask(); WaitOne(); while (IsRun) { cTask.RunTask(cTask); MathNextTask(); WaitOne(); } } #endregion #region 关机 public void CloseWindows(DateTime dt) { IsRun = true; Action hand = new Action(this.CloseWindows_Action); hand.BeginInvoke(dt, null, null); } void CloseWindows_Action(DateTime dt) { TimeSpan ts = dt - DateTime.Now; if (ts.TotalSeconds < 1) return; AutoReset.WaitOne(ts, true); if (IsRun == false) return; SystemInfo.CloseWindows(); } #endregion } public class TaskModel { public Action RunTask = null; public DateTime NextTime = DateTime.Today; /// /// 间隔时间(分钟) /// public int Interval = 0; public object CustomModel = null; } }