问题
my code executes every 5 minutes, within the 5 minutes if date changes my code will not run. how to handle this, please help
I think i need to check currenttime.addminutes(5) and check if date changes and if date changes then need to set timer so that my code can run can any one help he how to implement this
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);
}
}
}
回答1:
The Problem with my above code is that I was trying to check elapsed time and compare it to zero. Instead, if the date change is identified, and check it with the current date for date change which obviously means the time has elapsed so the code will run and create report successfully.
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;
}
}
//}
}
来源:https://stackoverflow.com/questions/35714505/running-windows-service-at-midnight