DEV Community

Juarez Júnior
Juarez Júnior

Posted on

Task Scheduling with Quartz.NET

Quartz.NET is an open-source library that simplifies task (job) scheduling in .NET applications. It is robust and offers a wide range of scheduling features, including recurring tasks, cron expression-based execution, and much more. Quartz.NET is widely used in enterprise applications to schedule and automate background tasks. In this example, we will configure Quartz.NET to schedule and execute a recurring task using a cron expression.

Libraries:

To use the Quartz.NET library, install the following NuGet package in your project:

Install-Package Quartz
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Quartz;
using Quartz.Impl;
using System;
using System.Threading.Tasks;

public class ExampleTask : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        Console.WriteLine($"Task executed at: {DateTime.Now}");
        return Task.CompletedTask;
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        // Creating a task scheduler
        IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();
        await scheduler.Start();

        // Defining the job to be scheduled
        IJobDetail job = JobBuilder.Create<ExampleTask>()
            .WithIdentity("exampleTask", "group1")
            .Build();

        // Creating a cron trigger to execute the task every minute
        ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("triggerExample", "group1")
            .StartNow()
            .WithCronSchedule("0 * * ? * *") // Executes every minute
            .Build();

        // Scheduling the job
        await scheduler.ScheduleJob(job, trigger);

        Console.WriteLine("Task scheduled. Press Enter to exit...");
        Console.ReadLine();

        await scheduler.Shutdown();
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we use Quartz.NET to create a task scheduler that runs a job called ExampleTask. The ExampleTask class implements the IJob interface, which contains the Execute method where the task’s logic is defined. The task prints the execution date and time to the console. The task is scheduled using a cron trigger, which is configured to execute the task every minute using the cron expression "0 * * ? * *". The scheduler starts executing the task immediately and will continue to do so every minute until the program is closed.

Conclusion:

Quartz.NET is a powerful and flexible library for task scheduling in .NET applications. It supports cron expressions, multiple job executions, and various types of triggers, making it a robust solution for automating background tasks. It is widely used in enterprise systems for complex scheduling scenarios.

Source code: GitHub

Top comments (0)