SQL Tidsstyrte jobber

Episerver Scheduled jobs - Make it fail!

According to the Episerver User Guide, 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?

Skjermbilde fra Episerver admin mode som viser at en jobb har kjørt en gang, med status suksess, selv om en melding sier den har feilet.

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!

Skjermbilde fra Episerver admin mode som viser at jobben nå får status feilet.

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.

Skjermbilde fra SQL Management studio som viser at jobben feilet.

That's it!