当前位置:网站首页>Using quartz under. Net core -- operation transfer parameters of [3] operation and trigger
Using quartz under. Net core -- operation transfer parameters of [3] operation and trigger
2022-04-23 17:10:00 【Tomato Warrior】
Catalog
In the last one , We have a brief understanding of what a job is and its context , And the unique identification of the job , Next, we will continue to understand the transfer parameters of the operation
1、 Instance of job
Every time the scheduler executes a job Execute() Before method , Will create a new instance of the job
That means :
1、 The homework we wrote , Must have an unambiguous constructor
2、 stay job There is no point in defining data fields in a class , Because the scheduler creates a new instance every time , These fields will not be maintained .
2、JobDataMap
JobDataMap Can provide serializable objects
.JobDataMap
yes IDictionary
Interface implementation , It also has some convenient methods for storing and retrieving basic types of data .
JobDataMap
There are also some auxiliary methods in , such as GetKeys、Put 、GetInt wait , I won't go into details here
We created before modifying jobdetail Code for , Use UsingJobData Add one more key yes "name" The value is "zhangsan" Data item
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "jobGroup1")
.UsingJobData("name","zhangsan")
.Build();
Then modify the specific Job class , To receive our parameters
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
JobDataMap dataMap = context.JobDetail.JobDataMap;
string name = dataMap.GetString("name");
await Console.Out.WriteLineAsync($"{DateTime.Now}:{name}");
}
}
Here is the output :
Be careful : This kind of writing parameters directly in the form of string is not friendly ,Quartz Prompt us , If we use the function of persistent data , Well, it's probably because of the modification of the parameters key And cause serialization problems , Here, let's take a look at the example given by the official :
stay job Define parameter constants in
using System;
using System.Threading.Tasks;
namespace Quartz.Examples.Example04
{
public class ColorJob : IJob
{
public const string FavoriteColor = "favorite color";
public const string ExecutionCount = "count";
public virtual Task Execute(IJobExecutionContext context)
{
// Grab and print passed parameters
JobDataMap data = context.JobDetail.JobDataMap;
var favoriteColor = data.GetString(FavoriteColor);
int count = data.GetInt(ExecutionCount);
...
}
}
}
Pass values through constants
IJobDetail job2 = JobBuilder.Create<ColorJob>()
.WithIdentity("job2", "group1")
.Build();
job2.JobDataMap.Put(ColorJob.FavoriteColor, "Red");
job2.JobDataMap.Put(ColorJob.ExecutionCount, 1);
Of course , You can also use other methods , For example, write your own class mapping and so on
3、 Receive parameters with
If you add a job class with set Properties of the accessor , These properties are related to JobDataMap The key name in corresponds to , be Quartz Default JobFactory The implementation will automatically call these when instantiating the job setter, Avoid writing your own code to get parameters . Please note that , Use customization JobFactory when , This function is not maintained by default .
We modify HelloJob Code
public class HelloJob : IJob
{
public string Name { private get; set; }
public async Task Execute(IJobExecutionContext context)
{
JobDataMap dataMap = context.JobDetail.JobDataMap;
await Console.Out.WriteLineAsync($"{DateTime.Now}:{Name}");
}
}
Note that attribute names start with uppercase , I use lowercase here, which is invalid
4、 Trigger parameters
When we need the same job to pass different parameters according to different triggers , This is very useful
If the trigger parameter has the same name as the job parameter , That will replace the operation parameters
//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()
.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);
As you can see from the code above , We have defined in our own job instance name Parameters
And in The same name is also defined in both triggers name Parameters
Here are the results :
版权声明
本文为[Tomato Warrior]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553457856.html
边栏推荐
- ClickHouse-数据类型
- groutine
- [registration] tf54: engineer growth map and excellent R & D organization building
- Further optimize Baidu map data visualization
- Shell-sed命令的使用
- [pimf] openharmony paper Club - what is the experience of wandering in ACM survey
- 1-5 nodejs commonjs specification
- El cascade and El select click elsewhere to make the drop-down box disappear
- 【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
- Shell-sort命令的使用
猜你喜欢
Quick install mongodb
TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
Change the password after installing MySQL in Linux
Understanding of RPC core concepts
oracle 中快速获取表的列名列表
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
EF core in ASP Generate core priority database based on net entity model
线性代数感悟之2
Detailed explanation of C webpai route
Shell script -- shell programming specification and variables
随机推荐
RTKLIB 2.4.3源码笔记
Devexpress GridView add select all columns
Milvus 2.0 质量保障系统详解
Understanding of RPC core concepts
Summary of common websites
文件操作《二》(5000字总结篇)
Baidu Map Case - modify map style
VsCode-Go
First knowledge of go language
线性代数感悟之2
ClickHouse-数据类型
Perception of linear algebra 2
Baidu Map 3D rotation and tilt angle adjustment
MySQL master-slave configuration under CentOS
The new MySQL table has a self increasing ID of 20 bits. The reason is
Nifi fast installation and file synchronization
Input file upload
Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
Shell-sed命令的使用
Baidu Map Case - Zoom component, map scale component