当前位置:网站首页>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
边栏推荐
- [PROJECT] small hat takeout (8)
- Input file upload
- MySQL restores data through binlog file
- Detailed explanation of C webpai route
- Error in v-on handler: "typeerror: cannot read property 'resetfields' of undefined"
- Detailed explanation of Milvus 2.0 quality assurance system
- Handwritten event publish subscribe framework
- 手写事件发布订阅框架
- JS to find the character that appears three times in the string
- Shell-入门、变量、以及基本的语法
猜你喜欢
Milvus 2.0 détails du système d'assurance de la qualité
STM32__ 03 - beginner timer
Getting started with JDBC
Idea of batch manufacturing test data, with source code
C# Task. Delay and thread The difference between sleep
Devexpress GridView add select all columns
TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
feign报400处理
Nodejs installation and environment configuration
RPC核心概念理解
随机推荐
Generation of barcode and QR code
ClickHouse-表引擎
Website_ Collection
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
Promise (I)
1-2 characteristics of nodejs
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
Signalr can actively send data from the server to the client
Use of shell sed command
RTKLIB 2.4.3源码笔记
自定义my_strcpy与库strcpy【模拟实现字符串相关函数】
Shell - introduction, variables, and basic syntax
[C#] 彻底搞明白深拷贝
Net standard
Interface document yaml
Freecodecamp ---- budget & category exercise
VsCode-Go
First knowledge of go language
SQL database
How vscode compares the similarities and differences between two files