public DayTimeSpan(DayTimePoint s, DayTimePoint e) { if (s > e) { throw new Exception("TimeSpan构造错误,TimeSpan只支持同一天的一个时间段,并且开始时间点不能大于结束时间点。"); } _tpPair = new Pair <DayTimePoint, DayTimePoint>(s, e); }
/// <summary> /// 每天定时执行一次任务 /// </summary> /// <param name="startTimePoint">运行时间点</param> /// <param name="act">程序代码</param> /// <param name="errtry">错误重试次数</param> /// <param name="runintime">是否立刻运行一次,如果不是,则下一次运行,默认false</param> /// <returns></returns> public static Timer SetInterval(DayTimePoint startTimePoint, Func <bool> act, int errtrytimes = 1, bool runintime = false) { SingleTimer timer = new SingleTimer(1); timer.ErrorTryTimes = errtrytimes; timer.Elapsed += (o, e) => { lock (timer) { if (timer.IsRuning) { return; } if (timer.LastStartTime == DateTime.MinValue && DateTime.Now < startTimePoint) { return; } if (!runintime && timer.LastStartTime == DateTime.MinValue && DateTime.Now.Subtract(startTimePoint.ToDateTime()).TotalHours > 1) { return; } timer.IsRuning = true; timer.Stop(); } DateTime starttime = DateTime.Now; timer.LastStartTime = starttime; bool actresult = false; try { actresult = act(); timer.Success(); } catch (Exception ex) { timer.Error(ex); if (timer.ErrorTimes < timer.ErrorTryTimes) { timer.Restart(timer.ErrorInterval); return; } else { timer.LastError = ex; } } if (actresult) { timer.Kill(); } else { timer.Restart(startTimePoint.GetNextTimePoint(starttime).Subtract(DateTime.Now).TotalMilliseconds); } timer.LastFinishTime = DateTime.Now; }; timer.Start(); return(timer); }
/// <summary> /// 时间是否落在时间段内 /// </summary> /// <param name="dt"></param> /// <returns></returns> public bool IsTimeInSpan(DateTime dt) { DayTimePoint tempTP = new DayTimePoint(dt.Hour, dt.Minute); return(tempTP >= TimeBegin && tempTP <= TimeEnd); }