Specific use of quartz.net

Time:2022-7-30

1、 What is quartz.net?

Quartz. Net is a fully functional open source job scheduling system, which can be used from the smallest applications to large enterprise systems.

Quartz.net is pure. It is a.Net assembly and the c# implementation of quartz, a very popular Java job scheduling system.

2、 What can quartz.net do?

Quartz. Net has many features, such as database support, clustering, plug-ins, support for cron like expressions, etc. it is very suitable for regular work, such as regular polling, database synchronization, regular email notification, regular data processing, etc.

Quartz. Net allows developers to schedule jobs based on time intervals (or days). It realizes the many to many relationship between jobs and triggers, and can associate multiple jobs with different triggers.

Quartz. Net applications can reuse jobs from different events, and can also combine multiple jobs for an event.

I choose quartz this time Net version is 3.3.3

Here is an important point: there is a certain difference between the 3.x version and the 2.x version

Official documents of quartz.net:https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html

3、 Asp Net core how to use quartz.net?

First we need to create an asp Net core web project, the creation process will not be shown. What I create is an API project, using the traditional three-tier architecture.

After the project is created, we need to install quartz.aspnetcore and quartz.extensions.dependencyinjection in nuget package manager

It is different from the use of 2.x, because the version I use is 3.3.3 (the latest version at this time). We are not like the traditional creation of scheduling center classes. Traditionally, the definition of the job factory class [resetjobfactory], the control center class [schedulercenter], and the regular work class [regularwork] (as shown in the figure below) are not introduced here.

Just create a regular work class [regularwork] and inherit quartz Net, I_ RegularWork_ Bll can be injected into regularwork, which requires usemicrosoftdependencyinjectionjobfactory


 public class RegularWork : IJob
    {
    private readonly I_RegularWork_BLL I_bll;
    public RegularWork(I_RegularWork_BLL Ibll)
    {
        I_bll = Ibll;
    }
 
    public Task Execute(IJobExecutionContext context)
    {
        Input_RoomType model = new Input_RoomType();
        model.currentPage = 1;
        model.pageSize = 1;
        var result = I_bll.getRoomTypeList(model);
 
        return Task.Run(() =>
        {
            using (StreamWriter sw = new StreamWriter(@"F:/Quartz-NET.txt", true, Encoding.UTF8))
            {
               sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff =>") + JsonConvert.SerializeObject(result));
            }
        });
    }
}

Register regularwork through services in the configureservices method of startup.cs

//Work unit of quartz
 services.AddTransient<RegularWork>();

Quartz dispatch center is added in configureservices method. Quartz.Extensions. Dependencyinjection provides integration with Microsoft dependency injection, although quartz provides two built-in alternatives for job factories, which can be configured by calling usemicrosoftdependencyinjection jobfactory or usemicrosoftdependencyinjection scopedjobfactory (deprecated).

From quartz Net 3.3.2, all jobs generated by the default job factory are scope jobs, and usemicrosoftdependencyinjectionscopedjobfactory should no longer be used.

Addjob – add a work unit; Startnow means that the job will be executed now;

Withinterval is used to execute time policy execution rules;

TimeSpan. Fromseconds refers to the time interval of execution, in seconds; Repeatforever represents repeated work, and withrepeatcount (5) can be used instead of repeatforever; Withrepeatcount (5) represents 5 times

//Quartz dispatching center
    services.AddQuartz(q =>
    {
        //For injection
        q.UseMicrosoftDependencyInjectionJobFactory();
        //Basic quartz scheduler, job, and trigger configuration
        var jobKey = new JobKey("RegularWork", "regularWorkGroup");
        q.AddJob<RegularWork>(jobKey, j => j
            .WithDescription("My regular work")
        );
        q.AddTrigger(t => t
            .WithIdentity("Trigger")
            .ForJob(jobKey)
            .StartNow()
            .withsimpleschedule (x = > x.withinterval (timespan.fromseconds (10)) // start seconds 10s
            .repeatforever()) // keep working
            .WithDescription("My regular work trigger")
        );
});

Add quartz service in configureservices method

//Asp.net core Hosting - add quartz server
 services.AddQuartzServer(options =>
 {
     //When closing, we hope the operation can be completed normally
     options.WaitForJobsToComplete = false;
 });

Complete code

//Work unit of quartz
    services.AddTransient();
    //Quartz dispatching center
    services.AddQuartz(q =>
    {
        //For injection
        q.UseMicrosoftDependencyInjectionJobFactory();
        //Basic quartz scheduler, job, and trigger configuration
        var jobKey = new JobKey("RegularWork", "regularWorkGroup");
        q.AddJob(jobKey, j => j
            .WithDescription("My regular work")
        );
        q.AddTrigger(t => t
            .WithIdentity("Trigger")
            .ForJob(jobKey)
            .StartNow()
            .withsimpleschedule (x = > x.withinterval (timespan.fromseconds (10)) // start seconds 10s
            .withrepeatcount (5)) // keep working
            .WithDescription("My regular work trigger")
        );
});
//Asp.net core Hosting - add quartz service
services.AddQuartzServer(options =>
{
    //When closing, we hope the operation can be completed normally
    options.WaitForJobsToComplete = false;
});

At this time, we start the project and start the regular work. At this time, the injection is valid. After querying the data, the results are printed in the quartz-net.txt file under disk f (as shown in the following figure).

4、 Cron expression of quartz

Official document introduction:https://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html

It consists of 7 segments: second minute hour day month week year (optional)
“-“: indicates the range mon-wed indicates Monday to Wednesday
“,”: means to list Mon, and web means Monday and Wednesday
“*”: the table is “every”, monthly, daily, weekly, annual, etc
“/”: indicates the increment: 0/15 (in the minute segment) every 15 minutes, starting after 0 minutes, 3/20 every 20 minutes, starting after 3 minutes
“?” : It can only appear in the day and week segments, indicating that no specific value is specified
“L”: it can only appear in the day and week segments. It is the abbreviation of last, the last day of a month and the last day of a week (Saturday)
“W”: refers to the working day, which is the nearest working day to the given value
“#”: indicates the day of the week in a month. For example, “6#3” indicates the third Friday of each month (1=sun… 6=fri, 7=sat)

Expression Meaning
0 0 12 * * ? Triggered at 12 noon every day
0 15 10 ? * * Triggered at 10:15 every morning
0 15 10 * * ? Triggered at 10:15 every morning
0 15 10 * * ? * Triggered at 10:15 every morning
0 15 10 * * ? 2005 Triggered at 10:15 a.m. every day in 2005
0 * 14 * * ? Triggered every 1 minute between 2 p.m. and 2:59 p.m. every day
0 0/5 14 * * ? Triggered every 5 minutes between 2 p.m. and 2:55 p.m. every day
0 0/5 14,18 * * ? Triggered every 5 minutes between 2 p.m. and 2:55 p.m. and between 6 p.m. and 6:55 p.m
0 0-5 14 * * ? Triggered every 1 minute between 2 p.m. and 2:05 p.m. every day
0 10,44 14 ? 3 WED Triggered at 2:10 and 2:44 p.m. on Wednesday in March every year
0 15 10 ? * MON-FRI Triggered at 10:15 am from Monday to Friday
0 15 10 15 * ? Triggered at 10:15 a.m. on the 15th of each month
0 15 10 L * ? Triggered at 10:15 a.m. on the last day of each month
0 15 10 L-2 * ? Fire at 10:15am on the 2nd-to-last last day of every month
0 15 10 ? * 6L Triggered at 10:15 a.m. on the last Friday of each month
0 15 10 ? * 6L Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L 2002-2005 Triggered at 10:15 a.m. on the last Friday of each month from 2002 to 2005
0 15 10 ? * 6#3 Triggered at 10:15 a.m. on the third Friday of each month
0 0 12 1/5 * ? Fire at 12pm (noon) every 5 days every month, starting on the first day of the month.
0 11 11 11 11 ? Fire every November 11th at 11:11am.

This is the end of this article about the specific use of quartz.net. More about quartz Net content, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]