当前位置:网站首页>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
边栏推荐
- VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
- Calculation formula related to tolerance analysis
- . net cross platform principle (Part I)
- SPC introduction
- Shell-入门、变量、以及基本的语法
- 快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
- Paging SQL
- websocket
- Simulation of infrared wireless communication based on 51 single chip microcomputer
- Get the column name list of the table quickly in Oracle
猜你喜欢

How vscode compares the similarities and differences between two files

Smart doc + Torna generate interface document

groutine

2.Electron之HelloWorld

Nodejs installation and environment configuration

Scope and scope chain in JS

Idea of batch manufacturing test data, with source code

Shell script -- shell programming specification and variables

Nacos + aspnetcore + Ocelot actual combat code

Rtklib 2.4.3 source code Notes
随机推荐
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
Use of shell awk command
[markdown notes]
Go language RPC communication
PHP efficiently reads large files and processes data
Generate random numbers with high quality and Gaussian distribution
AIOT产业技术全景结构-数字化架构设计(8)
Grpc gateway based on Ocelot
手写事件发布订阅框架
VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
Interface document yaml
Website_ Collection
ASP. Net core configuration options (Part 2)
Baidu Map Case - Zoom component, map scale component
杂文 谈谈古典的《拆掉思维里的墙》
How to implement distributed locks with redis?
Shell-cut命令的使用
TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
MySQL master-slave configuration under CentOS
Nodejs installation and environment configuration