/// <summary> /// 定时器每次跑起判断是否要确定执行ExecMethod /// </summary> public void TimerExec(RichTextConsole console, Action <AbstractTimerTask> refreshAction) { DateTime nowTime = DateTime.Now; TimeSpan intervalTimeSpan = nowTime - lastExecTime; if (intervalTimeSpan.TotalSeconds > IntervalTime && this.ExecStatus == ExecStatus.WaitExec) { this.ExecStatus = ExecStatus.Working; refreshAction(this); ThreadPool.QueueUserWorkItem(state => { try { lastExecTime = nowTime; ExecMethod(console); } catch (Exception ex) { console.Error("检测到【" + TimerName + "】定时任务,有未捕获的异常", ex); } finally { this.ExecStatus = ExecStatus.WaitExec; refreshAction(this); } }); } }
/// <summary> /// 定时任务执行的方法 /// </summary> /// <param name="console">控制台输出</param> public override void ExecMethod(RichTextConsole console) { console.Info($"执行{TimerName}定时任务开始...", isWriteLog: false); totalSearch++; if (totalSearch > 50)//总共查找次数达到50重新从第一页开始 { totalSearch = 1; pageIndex = 1; } JuHeResponse <JokesData> jokeResult = jokeProvider.SearchNewestJokes(pageIndex); if (jokeResult.error_code == 0) { List <JokeInfo> jokeList = jokeResult.result.data; List <JokeInfoDto> jokeDtoList = jokeList.Select(joke => new JokeInfoDto { Id = joke.hashId, Content = joke.content, CreateTime = TimeHelper.GetDateTime(joke.unixtime), UpdateTime = joke.updatetime }).ToList(); int saveRow = jokeInfoManage.SaveRangeJokes(jokeDtoList); if (saveRow > 0) { console.Info($"当前页码:{pageIndex},保存最新笑话数据成功,共保存{saveRow}条记录", isWriteLog: false); if (pageIndex > 1) { pageIndex++; } } else { console.Warn($"当前页码:{pageIndex},保存最新笑话数据0条,可能远程没有更新笑话", isWriteLog: false); nonDataIndex++; if (nonDataIndex > 2) { pageIndex = pageIndex * 2; nonDataIndex = 0;//快速双倍翻页后,累计没有保存到数据的次数清0 } else { pageIndex++; } } } else { console.Error($"定时获取最新笑话数据储存:error_code ={jokeResult.error_code},reason ={jokeResult.reason}"); } console.Info($"执行{TimerName}定时任务结束", isWriteLog: false); }