using System;
using System.Threading.Tasks;
namespace Mogafa.Unity.Common.Contexts
{
public abstract class TimesTaskAbstract
{
private int currentTimes;
private DateTime nextTime;
///
///
///
/// Delay time for task execution, unit: millisecond
/// The duration of the task interval, in milliseconds.
/// If it is 0, it means that it is executed only once, and maxTimes is meaningless
/// Maximum number of executions of the task. If it is 0, it means there is no limit
public TimesTaskAbstract(int delay, int interval, int maxTimes)
{
Id = Guid.NewGuid();
StartTime = DateTime.Now.AddMilliseconds(delay);
Interval = interval;
MaxTimes = maxTimes;
if (interval == 0)
{
MaxTimes = 1;
}
currentTimes = 0;
nextTime = StartTime;
IsPausing = false;
}
public Guid Id { get; set; }
public DateTime StartTime { get; set; }
///
///
///
public int Interval { get; set; }
public int MaxTimes { get; set; }
public bool IsPausing { get; private set; }
public bool IsFinished
{
get
{
if (MaxTimes == 0)
{
return false;
}
return currentTimes >= MaxTimes;
}
}
public Task Execute()
{
if (IsFinished || IsPausing)
{
return Task.CompletedTask;
}
Task task = null;
var canBeExecute = true;
var now = DateTime.Now;
if (now < nextTime)
{
canBeExecute = false;
}
if (canBeExecute)
{
task = ExecuteInternal();
currentTimes++;
nextTime = now.AddMilliseconds(Interval);
}
if (task == null)
{
task = Task.CompletedTask;
}
return task;
}
public void Pause()
{
IsPausing = true;
}
public void Resume()
{
nextTime = DateTime.Now.AddMilliseconds(Interval);
IsPausing = false;
}
protected abstract Task ExecuteInternal();
}
}