当前位置:网站首页>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
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
边栏推荐
- 线性代数感悟之1
- Further study of data visualization
- VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
- How to implement distributed locks with redis?
- 文件操作《二》(5000字总结篇)
- 线性代数感悟之2
- Shell-sed命令的使用
- Baidu Map Case - Zoom component, map scale component
- Nodejs installation and environment configuration
- Installing labellmg tutorial in Windows
猜你喜欢

Bottom processing of stack memory in browser

Scope and scope chain in JS

SQL database

VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN

Quick install mongodb

Milvus 2.0 détails du système d'assurance de la qualité

VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN

Change the password after installing MySQL in Linux

自定义my_strcpy与库strcpy【模拟实现字符串相关函数】

线性代数感悟之1
随机推荐
Deep understanding of control inversion and dependency injection
Handwritten event publish subscribe framework
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
Milvus 2.0 質量保障系統詳解
【题解】[SHOI2012] 随机树
MySQL modify master database
[markdown notes]
TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
Detailed explanation of Niuke - Gloves
Baidu Map Case - Zoom component, map scale component
ASP. NET CORE3. 1. Solution to login failure after identity registers users
Further optimize Baidu map data visualization
手写事件发布订阅框架
Get the column name list of the table quickly in Oracle
Preliminary understanding of promse
线性代数感悟之1
The new MySQL table has a self increasing ID of 20 bits. The reason is
Customize my_ Strcpy and library strcpy [analog implementation of string related functions]
New keyword learning and summary