当前位置:网站首页>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
边栏推荐
- MySQL modify master database
- On lambda powertools typescript
- SQL database
- Shell-sed命令的使用
- PostgreSQL column storage and row storage
- TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
- AIOT产业技术全景结构-数字化架构设计(8)
- Understanding of RPC core concepts
- How to implement distributed locks with redis?
- JS to find the character that appears three times in the string
猜你喜欢
C# Task. Delay and thread The difference between sleep
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
Detailed explanation of C webpai route
【WPF绑定3】 ListView基础绑定和数据模板绑定
ASP. NET CORE3. 1. Solution to login failure after identity registers users
1-4 configuration executable script of nodejs installation
Lock锁
Document operation II (5000 word summary)
Quick install mongodb
Shell脚本——Shell编程规范及变量
随机推荐
Error in v-on handler: "typeerror: cannot read property 'resetfields' of undefined"
RPC核心概念理解
Detailed explanation of Niuke - Gloves
Your brain expands and shrinks over time — these charts show how
JSON deserialize anonymous array / object
Rtklib 2.4.3 source code Notes
About stream flow, write it down briefly------
ASP. Net core reads the configuration file in the class library project
Paging the list collection
Website_ Collection
Further optimize Baidu map data visualization
[C] thoroughly understand the deep copy
groutine
Some problems encountered in recent programming 2021 / 9 / 8
【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
Promise (IV)
Freecodecamp ---- budget & category exercise
1-4 configuration executable script of nodejs installation
ClickHouse-表引擎
Devexpress GridView add select all columns