using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PLCLinker
{
///
/// 计时器类,提供计算时间间隔与判断时长方法
///
class MyTimer
{
public static bool restart { get; set; }
public bool rolledBack { get; set; }
private DateTime startTime;
private DateTime endTime;
private bool recorded;
private bool displayed;
private int activationCount;
private TimeSpan timeSpan;
///
/// 构造函数
///
public MyTimer()
{
restart = false;
recorded = false;
displayed = false;
rolledBack = false;
activationCount = 0;
}
///
/// 开始计时
///
public void StartTiming()
{
recorded = false;
startTime = DateTime.Now;
}
///
/// 结束计时
///
public void EndTiming()
{
endTime = DateTime.Now;
timeSpan = endTime - startTime;
recorded = true;
}
///
/// 获取时间间隔
///
/// 返回TimeSpan对象
public TimeSpan GetInterval()
{
if (recorded)
return timeSpan;
else
return new TimeSpan();
}
///
/// 判断时长是否在范围内
///
/// 最小单位个数
/// 最大单位个数
/// 一单位对应秒数
/// /// 是否只在外界输出一次
/// 判断结果
public bool IsInBetween(int minCount, int maxCount, double secondsInUnit, bool displayOnlyOnce)
{
TimeSpan ts = GetInterval();
if (ts.TotalSeconds >= minCount * secondsInUnit && ts.TotalSeconds <= maxCount * secondsInUnit)
{
if (displayOnlyOnce && displayed)
return false;
else
{
displayed = true;
return true;
}
}
else
return false;
}
/// ///
/// 判断时长是否在范围内
///
/// 最小单位个数
/// 一单位对应秒数
/// /// 是否只在外界激活一次
/// /// 记录被激活次数
/// 判断结果
public bool IsLonger(int minCount, double secondsInUnit, bool displayOnlyOnce, out int activationCount)
{
TimeSpan ts = GetInterval();
activationCount = this.activationCount;
if (ts.TotalSeconds >= minCount * secondsInUnit)
{
if (displayOnlyOnce && displayed)
return false;
else
{
this.activationCount += 1;
activationCount = this.activationCount;
displayed = true;
return true;
}
}
else
return false;
}
}
}