Anders G. Nordby

Lead Consultant at Itera

Monthly Archives: October 2017

Episerver 7: ScheduledJob: Last Successful Run

In an Episerver 7 project I’m working on, I need a scheduled job to continue its work with all that has happened since its last run. So I created the following code to make the job figure out when it last had a successful run:

[ScheduledPlugIn(
	DisplayName = "Some Job",
	Description = "Some Job Reporting its Last Successful Run"
	)]
public class SomeJob : JobBase
{
	internal static Injected<ServiceAccessor<SchedulerDB>> DataAccess;

	private DateTime GetLastSuccessfulRun()
	{
		var maxDate = DateTime.MinValue;
		foreach (DataRow row in DataAccess.Service().ListLog(ScheduledJobId).Tables[0].Rows)
		{
			if (Converter.ToIntZero(row["Status"]) != 0)
				continue;

			var execution = ((DateTime)row["Exec"]).ToLocalTime();
			if (execution > maxDate)
				maxDate = execution;
		}

		return maxDate;
	}

	public override string Execute()
	{
		var lastSuccessfulRun = GetLastSuccessfulRun();
		return $"The job was last successfully run on {lastSuccessfulRun:s}";

		// TODO: Make the job do more than just report its last successful run...
	}
}

…of course the job (when it’s fully implemented) will do more than just report its last successful run…

Advertisements