Blog

Filter posts by Category Or Tag of the Blog section!

using QUARTZ.NET

Thursday, 04 April 2019

Quartz.NET is an open-source job scheduling library that can be used to schedule and execute jobs in .NET applications. It provides a simple and powerful API that allows developers to define jobs and triggers, and then execute them on a schedule.

 

Here's an example of how to use Quartz.NET in a C# console application:

 

First, install the Quartz.NET package using NuGet:

 

Install-Package Quartz

 

Then, create a job class that implements the IJob interface. This interface has a single method called Execute that will be called by Quartz.NET when the job is triggered:

 

public class MyJob : IJob

{

    public Task Execute(IJobExecutionContext context)

    {

        Console.WriteLine("Executing job...");

        return Task.CompletedTask;

    }

}

 

Next, create a job trigger using the CronScheduleBuilder class to specify a cron expression that defines the schedule for the job:

 

var trigger = TriggerBuilder.Create()

    .WithIdentity("MyTrigger")

    .WithSchedule(CronScheduleBuilder.CronSchedule("0/5 * * * * ?"))

    .Build();

 

Finally, create a job detail object that associates the job class with the trigger:

 

var jobDetail = JobBuilder.Create<MyJob>()

    .WithIdentity("MyJob")

    .Build();

 

Then, create a StdSchedulerFactory instance, which is used to create a scheduler that will execute the jobs:

 

var schedulerFactory = new StdSchedulerFactory();

var scheduler = await schedulerFactory.GetScheduler();



await scheduler.ScheduleJob(jobDetail, trigger);



await scheduler.Start();



Console.ReadLine();



await scheduler.Shutdown();


 

This is just a simple example, but Quartz.NET provides many other features, such as support for persistent job storage, job chaining, and more. Now let’s create another scheduler to run every 5 seconds, start the scheduler, wait for the user to press a key, and then shut down the scheduler. So create a class that implements the IJob interface. This class will define the code that you want to execute on a schedule. Here's an example:
 

public class MyJob : IJob

{

    private readonly IMyService _service;



    public MyJob(IMyService service)

    {

        _service = service;

    }



    public async Task Execute(IJobExecutionContext context)

    {

        await _service.CallServiceAsync();

    }

}

 

In this example, the MyJob class has a dependency on an IMyService interface, which defines the code that calls the service you want to run on a schedule.

Next, create a JobFactory class that will create instances of the MyJob class. Here's an example:

 

public class MyJobFactory : IJobFactory

{

    private readonly IServiceProvider _serviceProvider;



    public MyJobFactory(IServiceProvider serviceProvider)

    {

        _serviceProvider = serviceProvider;

    }



    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)

    {

        return _serviceProvider.GetService<MyJob>();

    }



    public void ReturnJob(IJob job)

    {

        // No need to do anything here

    }

}

 

In this example, the MyJobFactory class has a dependency on an IServiceProvider interface, which will be used to create instances of the MyJob class.

Next, configure Quartz.NET in your startup class. Here's an example:

 

public void ConfigureServices(IServiceCollection services)

{

    // Add Quartz.NET

    services.AddSingleton<IJobFactory, MyJobFactory>();

    services.AddSingleton<MyJob>();

    services.AddQuartz(q =>

    {

        q.UseMicrosoftDependencyInjectionJobFactory();

        q.ScheduleJob<MyJob>(trigger => trigger

            .WithIdentity("MyJob")

            .StartNow()

            .WithSimpleSchedule(schedule => schedule

                .WithIntervalInSeconds(5)

                .RepeatForever()));

    });

}



public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    // Start the Quartz.NET scheduler

    app.ApplicationServices.GetService<IScheduler>().Start();

}

 

In this example, we're adding the MyJobFactory, MyJob, and IScheduler instances to the service collection. We're also configuring Quartz.NET to use the Microsoft Dependency Injection job factory, and scheduling a job to run every 5 seconds. That's it! Now, every 5 seconds, the MyJob class will be instantiated and its Execute method will be called, which will call the service you want to run on a schedule.

comments powered by Disqus