In this tutorial, you will learn how to enable/disable an Episerver scheduled task in code. If you need to run a background task within your Episerver website, you'll likely need to create an Episerver scheduled task. Scheduled tasks are a great way to run small bits of the functionality on a regular basis, like an import task etc... If you have ever needed or wondered how to enable/disable a scheduled task in code, this guide is for you.
Before I continue, would like to clarify another point on scheduled tasks. Episerver scheduled tasks will run in the same application pool as your website. If you need to consistently run a lot of processor-heavy tasks that consume a lot of your website's resources, I recommend that you look into Hangfire instead. HangFire is a more advanced scheduler that is worth considering in certain circumstances.
How Do I Access My Scheduled Tasks In Code
If you want to start messing around with scheduled tasks in code, you'll need to know about the
IScheduledJobRepository interface. The
IScheduledJobRepository API will provide access to perform functions like delete, get and update the currently scheduled tasks. To use the
IScheduledJobRepository in code, you can access it like this:
NOTE: On Line1, I am using
ServiceLocator. Using service locator is considered an anti-pattern. The code is written this way to make it easier to read in this article. Use constructor injection in your final solution!
Like most Episerver utility helpers, the code is pretty simple. If you want to disable a task, you can use this code:
IScheduledJobRepository also provides a method that will allow you to start querying what jobs are running, you can disable a task and you can also enable it as well. There are also some useful properties on the scheduled task object, so you can query how long a job has been running. Using the range of methods exposed by
IScheduledJobRepository, you could create a job that checked if all the other scheduled tasks ran successfully, if any failed you could then auto-generate an email:
If you look at your Episerver database, you can see the data for these tasks within the
tblSchedule table. That pretty much covers most of
IScheduledJobRepository. You are now a scheduling ninja 🐱👤🐱👤🐱👤 Happy Coding 🤘