public void StartRepeatDownload() { //为了预留一定的误差冗余,特意把触发间隔时间设为 60.5 秒而不是 60 秒。 RepeatInfo infoNext = new RepeatInfo(DefaultNextMinute0SecondCalculator, TimeSpan.FromSeconds(60.5)); //为了预留一定的误差冗余,特意把触发间隔时间设为 60.5 秒而不是 60 秒。 RepeatInfo infoCurrent = new RepeatInfo(TimeSpan.FromSeconds(0), DefaultNextMinute0SecondCalculator); #region 测试之用: ////1 //RepeatInfo infoNext = new RepeatInfo(TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(15)); //RepeatInfo infoCurrent = new RepeatInfo(TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(15)); ////2 //RepeatInfo infoNext = new RepeatInfo(DefaultNextMinute0SecondCalculator, TimeSpan.FromSeconds(60)); //RepeatInfo infoCurrent = new RepeatInfo(TimeSpan.FromSeconds(0), DefaultNextMinute0SecondCalculator); #endregion downloadTimer = new Timer(RepeatDownloadData, infoNext, infoCurrent.DueTime, infoCurrent.Period); }
private void RepeatDownloadData(object repeatInfo) { if (repeatInfo == null || (false == repeatInfo is RepeatInfo)) { throw new ArgumentException("参数 repeatInfo 为 null 或不是 RepeatInfo 类型的实例!", "repeatInfo"); } RepeatInfo info = repeatInfo as RepeatInfo; List <SourceData> data = DataDownloader.DownloadData(); bool isSuccess = CombineSourceData(data); //如果合并不成功(即:data 数据为空或者没有最新这一分钟的数据),则把触发时间改为 1 秒之后,即 1 秒后重新触发下载操作。 if (false == isSuccess) { info.Change(TimeSpan.FromSeconds(1), DefaultNextMinute0SecondCalculator); } //否则,如果合并成功,则把触发时间设为正常的 “在下一分钟开始”。 else { info.Change(DefaultNextMinute0SecondCalculator, TimeSpan.FromSeconds(60.5)); } info.ChangeTimer(downloadTimer); //通过 RepeatInfo 对象的参数来更新 Timer 对象的触发参数。 //上面的这个 “info.ChangeTimer(downloadTimer);” 写法替代了下面的这种。 //downloadTimer.Change(info.DueTime, info.Period); }
public void ChangeTimerState(TimeSpan dueTime, TimeSpan period) { RepeatInfo info = new RepeatInfo(dueTime, period); info.ChangeTimer(downloadTimer); }