Blog about tips & tricks for CMS enhancement

eric.petersson

Display elapsed time for scheduled jobs in Episerver


When working with scheduled jobs I have noticed quite often that some of the administrators are requesting how long some jobs have been running.

This is quite a common feature request. I ended up creating a base class on my own for implementing this kind of need:

public class MyApplicationScheduledJobBase : ScheduledJobBase
{
    private DateTime _started;

    public MyApplicationScheduledJobBase()
    {
        _started = DateTime.Now;
    }

    public string ElapsedTime => TimeSpan.FromSeconds(Math.Ceiling((DateTime.Now - _started).TotalSeconds)).ToString();

    public override string Execute()
    {
        throw new NotImplementedException();
    }
}

So when implementing a new job, I always fall back on the following setup by inheriting the base class to retrieve the property:

[ScheduledPlugIn(DisplayName = "My Job", SortIndex = 999999)]
public class MyJob : MyApplicationScheduledJobBase
{
    public override void Stop()
    {
        _stopSignaled = true;
    }

    public override string Execute()
    {
       // your business logic and implementations here
        return ExecuteJob();
    }

    private string ExecuteJob()
    {
        OnStatusChanged($"Starting job of {this.GetType()}. The job has been running for {ElapsedTime}");
    }
}

The result

When running a job you will get a status message updated with the job's duration time successively about every 5-10 seconds.

Elapsed time displaying in status message for scheduled job in Episerver