Tuesday, January 21, 2020

Run Sitecore scheduled task at the same time every day


https://briancaos.wordpress.com/2011/06/28/run-sitecore-scheduled-task-at-the-same-time-every-day/


Run Sitecore scheduled task at the same time every day

Yesterday I helped a user on stackoverflow with this question:
Is it possible to run a Sitecore scheduled task at the exact time every day?
The quick answer is no. But it’s possble to get it close to the same time every day.
Scheduled tasks are run in sequence by the Sitecore scheduler. The scheduler checks within a certain interval (defined in the web.config in the /scheduling/frequency and /scheduling/agent settings) for tasks to be run. If a task is over due, it is run, and the time where the task finished is recorded as the next checkpoint.
It is not possible to define a certain time a day the task needs to run. It’s only possible to determine which days a task needs to run, and the interval.
So how do you make a task run once a day, at a certain time?
Well, instead of configuring the task to run every 23:59:59, I make my task run every minute, but only executing the functionality once a day. Inside the task I check the time, and only if the time is inside a certain interval I execute the functionality.
Here is how to do it:
1) Create yout task and make it run every 1 minute or 5 minutes (or at least twice as often as your interval).
2) Define an interval where the task is allowed to run. For example at night between 01:00 am and 02:00 am.
3) Build your task in the following manner:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class TaskRunningOnceAday
{
  public void Execute(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduleItem)
  {
    if (!IsDue(scheduleItem))
      return;
 
    // EXECUTE MY FUNCTIONALITY
  }
 
  /// <summary>
  /// Determines whether the specified schedule item is due to run.
  /// </summary>
  /// <remarks>
  /// The scheduled item will only run between defined hours (usually at night) to ensure that the
  /// task is run once a day
  /// Make sure you configure the task to run at least double so often than the time span.
  /// </remarks>
  private bool IsDue(ScheduleItem scheduleItem)
  {
    DateTime time;
    DateTime time2;
 
    DateTime.TryParse("01:00:00", out time);
    DateTime.TryParse("02:00:00", out time2);
 
    return (CheckTime(DateTime.Now, time, time2) && !CheckTime(scheduleItem.LastRun, time, time2));
  }
 
  private bool CheckTime(DateTime time, DateTime after, DateTime before)
  {
    return ((time >= after) && (time <= before));
  }
 
}
The scheduleItem.LastRun property contains the date and time from where the task was last run.
The function “IsDue” checks to see if the task has run within the selected interval. If not, it returns true and the task may execute it’s functionality. If it has already run, it returns false, and the functionality is skipped.

No comments:

Post a Comment