0

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.

1
  • I know this is not super helpful, but this kind of thing is why I never use the Sitecore Task scheduler. Use Akshay's SiteCron module, it is so much more accurate and reliable. So not a fix for your code, but maybe an alternative to get you running.
    – Richard Seal
    Commented Oct 21, 2021 at 14:14

1 Answer 1

2

This behavior occurs if your scheduled task is set to run asynchronously. To avoid this behavior, be sure that the Async field of your scheduled task item is not checked:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.