我的代码每5分钟执行一次,如果日期更改,我会在5分钟内执行代码。如何处理,请帮助
我想我需要检查currenttime.addminutes(5)并检查日期 更改,如果日期更改,则需要设置计时器,以便我的代码可以 运行可以任何人帮助他如何实现这个
if (Daily == "true")//run daily at 11:59:59
{
DateTime currentTime = DateTime.Now;
int intervalToElapse = 0;
DateTime scheduleTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 23, 59, 59, 999);
if (currentTime <= scheduleTime)
intervalToElapse = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
else
intervalToElapse = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
_DailyTimer = new System.Timers.Timer(intervalToElapse);
if (_DailyTimer.Interval == 0)//if date changes this will be false and the code will not run
{
string tempFilename = Convert.ToString(tempDailyTime.TimeOfDay).Replace(":", "-") + ".xlsx";
if (!File.Exists(tempDir + "\\Daily" + "\\" + ReportName + "_" + tempFilename))
{
GenerateDailyReport(ReportName, ReportID, ConnectionString, ReportColumnName, ReportBQuery, "00:00:00", "23:59:59", tempDir + "\\Daily", tempFilename);
}
}
}
答案 0 :(得分:0)
上面代码的问题是我试图检查经过的时间并将其与零进行比较。相反,如果标识了日期更改,并使用当前日期更改进行检查,这显然意味着时间已过,因此代码将运行并成功创建报告。
private DateTime _lastRun = DateTime.Now.AddDays(-1);
if (Daily == "true")
{
//DateTime currentTime = DateTime.Now;
//int intervalToElapse = 0;
//DateTime scheduleTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 23, 59, 59, 999);
//if (currentTime <= scheduleTime)
// intervalToElapse = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
//else
// intervalToElapse = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
//_DailyTimer = new System.Timers.Timer(intervalToElapse);
//if (_DailyTimer.Interval == 0)
//{
if (_lastRun.Date < DateTime.Now.Date)
{
DateTime schTime = new DateTime(_lastRun.Year, _lastRun.Month, _lastRun.Day, 23, 59, 59, 999);
string tempFilename = Convert.ToString(tempDailyTime.TimeOfDay).Replace(":", "-") + ".xlsx";
if (!File.Exists(tempDir + "\\Daily" + "\\" + ReportName + "_" + tempFilename))
{
GenerateDailyReport(ReportName, ReportID, ConnectionString, ReportColumnName, ReportBQuery,Convert.ToString(_lastRun.Date), Convert.ToString(schTime), tempDir + "\\Daily", tempFilename);
_lastRun = DateTime.Now;
}
}
//}
}