当前位置:网站首页>Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
2022-04-23 17:11:00 【Tomato Warrior】
Catalog
1、DisallowConcurrentExecution Concurrent
3、PersistJobDataAfterExecution
4、 Other properties of the job
Previous section , We have done some in-depth understanding of homework , Especially the assignment transfer part , This time, , We'll look at some of the job's feature tags
1、DisallowConcurrentExecution Concurrent
We know ,Quartz All jobs in are asynchronous , Even if the same Job Multiple triggers for , He's still asynchronous
Let's give HelloJob Simulate a time-consuming operation
public class HelloJob : IJob
{
public string Name { private get; set; }
public async Task Execute(IJobExecutionContext context)
{
await Task.Delay(1000);// Simulation time operation
JobDataMap dataMap = context.JobDetail.JobDataMap;
await Console.Out.WriteLineAsync($"{DateTime.Now}:{Name}");
}
}
And give The same HelloJob Add two instances Trigger ( Copy the code from the previous section )
//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")
.UsingJobData("name","zhangsan")
.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()
.UsingJobData("name", "zhangsan")
.WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
.Build();
//5、 Create a second trigger , Bind to job
ITrigger trigger2 = TriggerBuilder.Create()
.WithIdentity("trigger2", "triggerGroup1")
.StartNow()
.UsingJobData("name", "lisi")
.WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
.ForJob(job)
.Build();
//6、 Bind trigger to job
await scheduler.ScheduleJob(job,trigger);
await scheduler.ScheduleJob(trigger2);
Let's take a look at the results

From the results, we can see that , The result output of the two tasks does not affect each other , Although we only created one job
But in some specific cases , We don't want one job It can be triggered multiple times at the same time , This requires features
[DisallowConcurrentExecution]
Take a look at the official introduction :
[DisallowConcurrentExecution]Yes, it can be added to Job Attributes of a class , This property tells Quartz Don't execute the given at the same time Job Definition ( Reference given Job class ) Multiple instances of .
Let's change the code , stay Hello Add features to [DisallowConcurrentExecution]
[DisallowConcurrentExecution]
public class HelloJob : IJob
{
public string Name { private get; set; }
public async Task Execute(IJobExecutionContext context)
{
await Task.Delay(1000);// Simulation time operation
JobDataMap dataMap = context.JobDetail.JobDataMap;
await Console.Out.WriteLineAsync($"{DateTime.Now}:{Name}");
}
}
Look at the results :

At the same time , The same Job Instances are not running at the same time
2、 About job instances
Here's a concept that's easy to confuse :
1、 One HelloJob Class can have multiple Job example , such as SayEnglishJob 、SayChineseJob
2、 One Job Instances can have multiple triggers
[DisallowConcurrentExecution] Is to limit specific examples , Instead of limiting classes
in other words ,SayEnglishJob example , There are multiple triggers , But at the same time , Can't run at the same time , however SayEnglishJob You can talk to SayChineseJob Running at the same time , Although they are instances created through the same class , But it doesn't affect .
3、PersistJobDataAfterExecution
The following is the original introduction
[PersistJobDataAfterExecution]is an attribute that can be added to the Job class that tells Quartz to update the stored copy of the JobDetail's JobDataMap after the Execute() method completes successfully (without throwing an exception), such that the next execution of the same job (JobDetail) receives the updated values rather than the originally stored values. Like the[DisallowConcurrentExecution]attribute, this applies to a job definition instance, not a job class instance, though it was decided to have the job class carry the attribute because it does often make a difference to how the class is coded (e.g. the 'statefulness' will need to be explicitly 'understood' by the code within the execute method).If you use the PersistJobDataAfterExecution attribute, you should strongly consider also using the
[DisallowConcurrentExecution]attribute, in order to avoid possible confusion (race conditions) of what data was left stored when two instances of the same job (JobDetail) executed concurrently.
Baidu translation :
[DisallowConcurrentExecution]Yes, it can be added to Job Attributes of a class , This property tells Quartz Don't execute the given at the same time Job Definition ( Reference given Job class ) Multiple instances of . Please note the wording here , Because it was chosen very carefully . In the example in the previous section , If “ SalesReportJob” With this attribute , be “ SalesReportForJoe” An instance of can only execute at a given time , But you can “ SalesReportForMike” Instances of execute simultaneously . Constraints are defined based on instances (JobDetail), Not based on the instance of the job class . however ,( stay Quartz In the design process of ) Decide to keep the attribute on the class itself , Because it often affects how classes are encoded .
[PersistJobDataAfterExecution]Yes, it can be added to Job Attributes of a class , This property tells Quartz stay Execute() Method completed successfully ( Don't throw exceptions ) Then update JobDetail Of JobDataMap Storage copy of , So that the same job can be executed next time (JobDetail) Receive updated values , Instead of the original stored value . And[DisallowConcurrentExecution]Properties are similar to , This applies to job definition instances , It does not apply to job class instances , Although it decides to let the job class carry this property , Because it often affects how classes are encoded ( for example ,“ There is a state ” Need by execute The code in the method explicitly “ understand ”.If you use PersistJobDataAfterExecution attribute , It should be strongly considered to use this
[DisallowConcurrentExecution]attribute , To avoid performing the same job at the same time (JobDetail) The confusion of what data is left to store when the two instances of ( Competition conditions ).
Now we have a need , Pass to HelloJob Parameters of name It needs to change
Modify the code :
modify HelloJob class : After the first execution , modify name Parameter values zhangsan by newName
public class HelloJob : IJob
{
public string Name { private get; set; }
public async Task Execute(IJobExecutionContext context)
{
await Task.Delay(1000);// Simulation time operation
JobDataMap dataMap = context.JobDetail.JobDataMap;
await Console.Out.WriteLineAsync($"{DateTime.Now}:{Name}");
dataMap.Put("name", "newName");// modify name value
}
}
modify Scheduling part , Remove redundant code
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")
.UsingJobData("name", "zhangsan")
.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();
}
Be careful , Here I removed a trigger , And remove the parameters on the trigger 了
Running results :

The output is not ideal , Parameter values zhangsan It didn't become... After the first run newName
At this time, we add [PersistJobDataAfterExecution] characteristic , And add [DisallowConcurrentExecution] (Quartz This is recommended )
[DisallowConcurrentExecution]
[PersistJobDataAfterExecution]
public class HelloJob : IJob
{
public string Name { private get; set; }
public async Task Execute(IJobExecutionContext context)
{
await Task.Delay(1000);// Simulation time operation
JobDataMap dataMap = context.JobDetail.JobDataMap;
await Console.Out.WriteLineAsync($"{DateTime.Now}:{Name}");
dataMap.Put("name", "newName");
}
}
See the operation results again :

name The value has been changed
4、 Other properties of the job
This is through JobDetail Object is a quick summary of other properties defined for the job instance :
Durability- If the job is non persistent , Once there are no more activity triggers associated with it , It will be automatically deleted from the scheduler . let me put it another way , The life of non persistent work is limited by the existence of its trigger .RequestsRecovery- If homework “ Request to restore ”, And in the scheduler “ Hard shutdown ” During the execution of ( namely , The process or machine it runs in a crash is shut down ), Then re execute the job under the following circumstances : The scheduler starts again . under these circumstances , TheJobExecutionContext.RecoveringProperty will return true.
5、JobExecutionException
Last , We need to inform you that
IJob.Execute(..)Some details of the method . You should start with execute The only exception type thrown by the method is JobExecutionException. therefore , Usually should be used “ try-catch” Block packaging execute The whole content of the method . You should also take some time to review JobExecutionException Documents , Because your job can use it to provide various instructions to the scheduler , To indicate how you want to handle exceptions .
版权声明
本文为[Tomato Warrior]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553457815.html
边栏推荐
- PostgreSQL column storage and row storage
- How to implement distributed locks with redis?
- 1-2 characteristics of nodejs
- 【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
- 快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
- Clickhouse SQL operation
- Paging the list collection
- EF core in ASP Generate core priority database based on net entity model
- ASP. Net core dependency injection service life cycle
- How does matlab draw the curve of known formula and how does excel draw the function curve image?
猜你喜欢

Nacos + aspnetcore + Ocelot actual combat code

Understanding of RPC core concepts

Devexpress GridView add select all columns

. net type transfer

org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su

Detailed explanation of Niuke - Gloves

Detailed explanation of C webpai route

Nodejs installation and environment configuration
![[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof](/img/71/14a17128dbe0f02edb4db3da479ef2.jpg)
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof

Milvus 2.0 質量保障系統詳解
随机推荐
Installing labellmg tutorial in Windows
Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
Nodejs installation and environment configuration
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
Lock lock
Feign report 400 processing
Use of shell sed command
ClickHouse-表引擎
Perception of linear algebra 2
Get the column name list of the table quickly in Oracle
How vscode compares the similarities and differences between two files
Further study of data visualization
【WPF绑定3】 ListView基础绑定和数据模板绑定
Website_ Collection
[PROJECT] small hat takeout (8)
Shell脚本——Shell编程规范及变量
Shell-sed命令的使用
ASP. NET CORE3. 1. Solution to login failure after identity registers users
PHP efficiently reads large files and processes data
Redis docker installation