I have a scheduled task that I recently realized isn't working properly. The Sitecore task is running, but in the code I have time check to make sure that it only runs within a one-hour window (2am to 3am), and only if it hasn't already run in that window:
protected virtual bool IsDue(ScheduleItem scheduleItem)
{
DateTime timeBegin;
DateTime timeEnd;
DateTime.TryParse("02:00:00", out timeBegin);
DateTime.TryParse("03:00:00", out timeEnd);
Sitecore.Diagnostics.Log.Info("IsDue timeBegin: " + timeBegin.ToString(), this);
Sitecore.Diagnostics.Log.Info("IsDue timeEnd: " + timeEnd.ToString(), this);
Sitecore.Diagnostics.Log.Info("IsDue now: " + DateTime.Now.ToString(), this);
Sitecore.Diagnostics.Log.Info("IsDue Last Ran: " + scheduleItem.LastRun.ToString(), this);
return (CheckTime(DateTime.Now, timeBegin, timeEnd) && !CheckTime(scheduleItem.LastRun, timeBegin, timeEnd));
}
private bool CheckTime(DateTime time, DateTime after, DateTime before)
{
return ((time >= after) && (time <= before));
}
I discovered through the logging that my code isn't running because it always returns IsDue = false
, because scheduleItem.LastRun is always equal to DateTime.Now. Here's a sample from my logs:
INFO IsDue timeBegin: 21.10.2021 02:00:00
INFO IsDue timeEnd: 21.10.2021 03:00:00
INFO IsDue now: 21.10.2021 02:04:18
INFO IsDue Last Ran: 21.10.2021 02:04:18
INFO Ended: Trial Import Schedule
INFO Trial Import Job not due at this time
Every instance in the logs is like this, where DateTime.Now is the exact same value as scheduleItem.LastRan. As a result my code never runs because it always thinks that the task has already run within the time window.