//************************************************************************
// author: yuzhengyang
// date: 2018.3.27 - 2018.6.3
// desc: 工具描述
// Copyright (c) yuzhengyang. All rights reserved.
//************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Azylee.Core.TaskUtils
{
public abstract class TaskSupport
{
private DateTime StartTime, LastRunTime;
///
/// 通过运行时间判断是否运行
///
public bool IsRun
{
get
{
if (LastRunTime.AddSeconds(Interval + 1000) > DateTime.Now)
return true;
return false;
}
}
///
/// 已启动
///
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()
{
StartTime = DateTime.Now;
if (!IsDestroy)
Task.Factory.StartNew(() =>
{
if (!IsStart)
{
_IsStart = true;
BeforeTODO();
do
{
LastRunTime = DateTime.Now;
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;
}
}
}