using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Y.Utils.TaskServiceUtils { public abstract class TaskServiceDaddy { /// /// 已启动 /// public bool IsStart { get { return _IsStart; } } /// /// 已启动(Protect) /// protected bool _IsStart = false; /// /// 取消标志 /// protected CancellationTokenSource CT = new CancellationTokenSource(); /// /// 任务循环间隔 /// protected int Interval = 1000; private bool IsDestroy = false; /// /// 设置任务间隔(0为不循环任务) /// /// /// public int SetInterval(int i) { Interval = i; return Interval; } /// /// 启动服务任务 /// public virtual void Start() { if (!IsDestroy) Task.Factory.StartNew(() => { if (!IsStart) { _IsStart = true; BeforeTODO(); do { TODO(); Thread.Sleep(Interval); } while (!CT.IsCancellationRequested && Interval > 0); AfterTODO(); } }); } /// /// 提前干点啥 /// public virtual void BeforeTODO() { } /// /// 干点啥 /// public abstract void TODO(); /// /// 完事儿干点啥 /// public virtual void AfterTODO() { } /// /// 停止服务任务 /// public virtual void Stop() { CT.Cancel(); IsDestroy = true; } } }