当前位置:网站首页>Using quartz under. Net core - [1] quick start

Using quartz under. Net core - [1] quick start

2022-04-23 17:10:00 Tomato Warrior

Catalog

1、 Environmental Science :

2、 New projects :

3、 install :

4、 To configure :

5、 Example :

6、 Complete code

Record Quartz Learning process , Hope to help those in need , If there is anything wrong, please correct it .


1、 Environmental Science :

development environment :vs2019、.net core 3.1、Quartz3.2.0

Official website :https://www.quartz-scheduler.net/

2、 New projects :

For future expansion , What I'm creating here is   .NET Core Web Applications (MVC)

3、 install :

Use nuget Manager installation : Search for :Quartz

4、 To configure :

The configuration is temporarily unavailable

5、 Example :

Tips : If this is right .net core I don't know much about it , You can learn about it before continuing

Registration service : Here, the dispatching factory is registered as a single example

// Register scheduler factory 
services.AddSingleton<ISchedulerFactory>(new StdSchedulerFactory());

 

modify HomeController

Inject into the dispatch plant

        // Dispatcher factory 
        private readonly ISchedulerFactory _schedulerFactory;

        // Constructor injection 
        public HomeController(ISchedulerFactory schedulerFactory)
        {
            // Injection scheduler factory 
            _schedulerFactory = schedulerFactory;
        }

Add custom Job  , Print current time

    public class HelloJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            await Console.Out.WriteLineAsync($"{DateTime.Now}");
        }
    }

modify Index For asynchronous

        public async Task<IActionResult> Index()
        {

            return View();
        }

Create a scheduler and execute tasks

 

        public async Task<IActionResult> Index()
        {
            //1、 Get scheduler instance from factory 
            IScheduler scheduler = await _schedulerFactory.GetScheduler();

            //2、 Start scheduling 
            await scheduler.Start();

            //3、 Define the job and bind it to our HelloJob class , The job name is job1  Job group name jobGroup1
            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("job1", "jobGroup1")
                .Build();

            //4、 Create an immediate trigger , Every interval 3 Second trigger once , The trigger name is trigger1, Trigger group name triggerGroup1
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "triggerGroup1")
                .StartNow()
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
                .Build();

            //5、 Bind trigger to job 
            await scheduler.ScheduleJob(job, trigger);

            return View();
        }

modify launchSettings.json file Delete IIS Relevant startup configuration

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Running results :

After operation , It will launch a command window and a browser page , And print the current time every three seconds


6、 Complete code

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;

namespace QuartzLearn
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            // Register scheduler factory 
            services.AddSingleton<ISchedulerFactory>(new StdSchedulerFactory());
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

HomeController.cs

using Microsoft.AspNetCore.Mvc;
using Quartz;
using System;
using System.Threading.Tasks;

namespace QuartzLearn.Controllers
{
    public class HomeController : Controller
    {
        // Dispatcher factory 
        private readonly ISchedulerFactory _schedulerFactory;

        // Constructor injection 
        public HomeController(ISchedulerFactory schedulerFactory)
        {
            // Injection scheduler factory 
            _schedulerFactory = schedulerFactory;
        }

        public async Task<IActionResult> Index()
        {
            //1、 Get scheduler instance from factory 
            IScheduler scheduler = await _schedulerFactory.GetScheduler();

            //2、 Start scheduling 
            await scheduler.Start();

            //3、 Define the job and bind it to our HelloJob class , The job name is job1  Job group name jobGroup1
            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("job1", "jobGroup1")
                .Build();

            //4、 Create an immediate trigger , Every interval 3 Second trigger once , The trigger name is trigger1, Trigger group name triggerGroup1
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "triggerGroup1")
                .StartNow()
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
                .Build();

            //5、 Bind trigger to job 
            await scheduler.ScheduleJob(job, trigger);

            return View();
        }
    }

    public class HelloJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            await Console.Out.WriteLineAsync($"{DateTime.Now}");
        }
    }
}

 

版权声明
本文为[Tomato Warrior]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553457928.html