At some point, any developer will have to write some code that must be executed at regular intervals. In SharePoint for instance, timerjobs were (!) very easy to create. In .NET, you could choose between scheduled tasks and windows services. While I was doing research on the ideal replacement for timerjobs in the new SharePoint app model, I came across Quartz.NET. In this post, I will show you which code you need to create timerjobs.
Before you can use Quartz.NET, you need to download their assembly. In NuGet, this is very easy. In the package manager console, you execute this command:
Install-Package Quartz
Now let’s create the task that needs to repeated by the timerjob. What needs to be executed depends entirely on the context, but at some place in your code you’ll need to leverage the Quartz API:`
Note that this class inherits the IJob interface, which has 1 contract: Execute(IJobExecutionContext).
Implementing this interface means you’ll be able to attach the code to the rest of the Quartz assembly. The next task is to tell Quartz.NET which job to launch at which intervals. We already have 1 element, I’ll talk about the other one now.
This code triggers my Hello World job every 5 seconds from the moment that I run my console application. This class creates the actual job that will to the regular work. Again notice this class inherits the IScheduledJob interface. Using the exposed methods from the factory it is possible to create an instance of the Quartz scheduler. Once that’s done, we need to provide an instance of the ITrigger instance and also an instance of the IJobDetail interface. The latter one is quite easy: replace the type between < > by your job and you’re done (unless you want to customize the behavior). The former interface requires you to define when the job should start to run and at what interval. Using method chaining you can do just so:
- The first method after Create allows you to start the job now or at a certain hour
- The second method after Create allows to define the interval, whether time-based or calendar-based.
There’s more configuration than this of course, but for basic jobs this will suffice. As soon as you call the RUN method, Quartz.NET will take care of your settings immediately. How you want to do this precisely, depends on the context of your application. It is possible to start your timers at application launch, you could create a console application that runs permanently, it could even take the form of a Windows Service (strongly advised), and for SharePoint projects this would be a very good alternative to the good old timerjob. In a future post, I’ll talk about all the different hosting possibilities.