I have a synchronous scheduled task that has to run everyday at 1:00 AM. But its last run time keeps increasing. How to fix this.
For the "Schedule
" field, the value is 20170419|20200422|127|23:59:59
I have a custom code to fire for the OnItemSaving
event, so as to always have the Last Run time as 1:00 AM
When the task runs for the first time, the last run field correctly gets updated to current date 1:00AM, but the next day I check, the last run is like 1:08, then 1:10....and it keeps on increasing.
config:
<events>
<event name="item:saving">
<handler type="MySite.XdbToJson, MySite" method="OnItemSaving">
</handler>
</event>
</events>
Code:
public void GetJsonData()
{
try
{
//this is the code that will execute when the scheduler is run
}
catch(Exception)
{
}
finally
{
Item scheduledTaskItem = GetItemFromMasterDB("{id of the scheduled task item}");
UpdateLastRunTime(scheduledTaskItem.ID);
}
}
private void UpdateLastRunTime(ID scheduledTaskID)
{
string isoLastRunTimeToSet = GetToBeSetLastRunIsoTime();
UpdateFieldValue(scheduledTaskID, new ID("{idOfLastRunFieldOfTask}"), isoLastRunTimeToSet);
}
private void UpdateFieldValue(ID itemID, ID fieldID, string fieldValue)
{
Database db = Configuration.Factory.GetDatabase("master");
Item item = db.GetItem(itemID, Context.Language, Version.Latest);
using (new SecurityDisabler())
{
item.Editing.BeginEdit();
using (new EditContext(item))
{
item.Fields[fieldID].Value = fieldValue;
}
item.Editing.EndEdit();
item.Editing.AcceptChanges();
}
}
private string GetToBeSetLastRunIsoTime()
{
string isoLastRunTimeToSet = string.Empty;
string lastRunTimeToSet = "01:00:00";
var parseDateString = string.Format("{0}/{1}/{2} {3}", DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Year, lastRunTimeToSet);
System.DateTime lastRunDateTimeToSet;
if (DateTime.TryParse(parseDateString, out lastRunDateTimeToSet))
{
isoLastRunTimeToSet = DateUtil.ToIsoDate(lastRunDateTimeToSet, false, true);
}
return isoLastRunTimeToSet;
}
public void OnItemSaving(object sender, EventArgs args)
{
Item scheduledTaskItem = Event.ExtractParameter(args, 0) as Item;
if (scheduledTaskItem.ID == new ID("{id of scheduled task}"))
{
string lastRunIsoDateTime = scheduledTaskItem.Fields["Last Run"].Value;
/*This condition will check if the last run time is as reqd. If not, it will proceed.
* If the last run field is not empty and also equal to the reqd. time, it means that the Json get data functions
* were executed and the last run time got updated. No need to continue in this case.
*/
if (!string.IsNullOrEmpty(lastRunIsoDateTime) && lastRunIsoDateTime != GetToBeSetLastRunIsoTime())
{
//check if the task is synchronous
if (scheduledTaskItem.Fields[Utility.CommonReferences.Templates.Schedule.Fields.Async].Value != "1")
{
using (new EventDisabler())
{
UpdateLastRunTime(scheduledTaskItem.ID);
}
}
}
}
}