Tags: Scheduled jobs SQL

Episerver Scheduled jobs - Make it fail!

According to the Optimizely User Documentation, a scheduled job is a service performing a task (job) at a given time interval. An administrator can start a job manually. By default, Episerver platform with Episerver CMS and Episerver Commerce includes several scheduled jobs. Some are enabled by default with preset values. You can develop customized scheduled jobs for specific website tasks.

If you write code that is likely to fail, it is good practice to wrap that section of code in a try-catch-clause and handle the exception. For scheduled jobs, it's the opposite! If something fails, be sure to throw that exception!

If something fails, you could of course catch the exception and maybe log the error. But when you're done handling the error, throw that exception!

Why? To display the status failed in admin mode GUI!

This is a pattern I see a lot.

[ScheduledPlugIn(DisplayName = "My scheduled job, that occasionally will fail")]
public class MyScheduledJob : ScheduledJobBase
{

    public override string Execute()
    {
        try
        {
            RunCodeThatWillFail();
        }
        catch
        {
            return "The job failed!";
        }

        return "The job succeded!";
    }
}

What happens when the job fails?

Screenshot from Epsierver admin mode showing a job that have run once, with status succeeded, even if the message says the job failed.

The status column claims the job succeeded, but it did not!

If we change the code slightly, and throw the exception, like this.

[ScheduledPlugIn(DisplayName = "My scheduled job, that occasionally will fail")]
public class MyScheduledJob : ScheduledJobBase
{

    public override string Execute()
    {
        try
        {
            RunCodeThatWillFail();
        }
        catch (Exception e)
        {
            LogManager.GetLogger().Error("The job failed: " + e);
            throw new Exception("The job failed!");
        }

        return "The job succeded!";
    }
}

Then the GUI shows the correct status: failed! Much better!

Screenshot from Episerver admin mode showing the job now has status failed.

This makes it easier to spot failing jobs looking at the history, or you could easily run a query against the database checking for jobs that have failed the last week.

Example:

SELECT si.[Name], sil.[Exec], sil.[Text], sil.[Duration], sil.[Server]
FROM [tblScheduledItem] si, [tblScheduledItemLog] sil
WHERE 
  si.[pkID] = sil.[fkScheduledItemId] AND 
  sil.[Exec] >= DATEADD(day,-7, GETDATE()) AND
  sil.[Status] = 2

The above query yields the following result.

Screenshot from SQL Management studio showing the job failed.

That's it!