Tags: Scheduled jobs

Episerver Scheduled jobs - Stop and restart!

Stop

Have you ever wanted to kill a long-running scheduled job? You can!

Just set the property IsStoppable to true, and override the Stop() method in ScheduledJobBase, like in the code example below.

The Stop() method will also be called if ASP.NET shuts down when the job is running, or if autoscaling in DXP shuts down the web app instance.

When a job is stoppable a new button is added the the user interface.

A screenshot from Episever admin mode, where you can see a button for stopping the job.

Restart

Restartable jobs were introduced in Episerver.CMS.Core 10.8. If the IIS crashes or is recycled when a job is running, the scheduler runs the job at the next scheduled time by default. A restartable job is started again to make sure it can run to completion. The job can restart on any available server.

Just set the Restartable property in the ScheduledPlugin attribute, like in the code example below.

[ScheduledPlugIn(DisplayName = "My scheduled job", Restartable = true)]
public class MyScheduledJob : ScheduledJobBase
{
    private bool _stopSignaled;

    public MyScheduledJob()
    {
        IsStoppable = true;
    }

    public override void Stop()
    {
        _stopSignaled = true;
    }

    public override string Execute()
    {
        for (var i = 0; i < Items.Count(); i++)
        {
            FinishItem(Items[i]);
            OnStatusChanged(i + " items finished.");

            if (_stopSignaled)
            {
                return "The job was stopped!";
            }
        }

        return Items.Count() + " items finished successfully.";
    }
}

That's it!