image A love-hate relationship with Samsung Knox Manage image Learning to learn

    Use Quartz.NET library for running jobs in a Windows service


    Have you ever wanted to run scheduled tasks within a running Windows Service? I do from time to time, and the discovery of this library made a life a lot easier. I’ve come across Quartz.NET, which gives you a rich job scheduling system.

    Quartz.NET is a pure .NET library written in C# and is a port of popular framework Quartz.

    Here you can find full list of features.

    Our use case

    Our customer wanted a solution where, they could run few sync jobs during the day from SQL database to other systems and services. They have on-prem infrastructure with Windows virtual machines. For that, we designed a Windows Service, which would implement a Quartz.NET jobs and run them at specific time. One thing to note, Quartz.NET supports cron job triggers, so you can easily write that instead of simple trigger every X seconds.

    So the solution is pretty straight forward.

    1. Create Windows Service Project in Visual Studio.
    2. Install Quartz.NET nuget package.
    3. Setup Quartz.NET library within the service.
    4. Implement a IJob interface, which does the processing.
    5. Install the Windows Service on the server and run it

    Below is a solution of the working Windows Service made out of 3 parts, app.config, UserSync.cs and UserSyncJob.cs. First let’s look at the configuration (app.config) which contains Active Directory login information (don’t store passwords there, this is for demo purposes only). The RunEveryXSeconds configuration runs a job every 300 seconds:

    Next let’s look at the Windows Service SyncService class. There is an important part JobBuilder.Create<UserSyncJob>() which ties UserSyncJob class to a job. Before that we set up the scheduler and after that the trigger and then run the scheduler:

    Now let’s look at the implementation of IJob, UserSyncJob class. Create a class UserSyncJob that implements IJob interface with method Execute(IJobExecutionContext context). A job below just writes the text “Job Run!” to a file:

    And that’s pretty much it. When you run the Windows service, the Job should be initialized and run for the first time and then every 300 seconds.

    And that’s all for this post! I hope you find it useful :).

    About Miha
    I've always been fascinated by computers. I am happy that I can work in this creative field of software development, where I can solve problems. I am also an avid cyclist :) and I love to learn...a lot!
    Related Posts
    • All
    • By Author
    • By Category
    • By Tag

    Leave a Reply