当前位置:网站首页>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
边栏推荐
- Smart doc + Torna generate interface document
- [PROJECT] small hat takeout (8)
- Generate random numbers with high quality and Gaussian distribution
- CentOS MySQL multi instance deployment
- 网络安全之渗透靶场实战详解
- Shell-cut命令的使用
- Path environment variable
- Freecodecamp ---- budget & category exercise
- Some problems encountered in recent programming 2021 / 9 / 8
- Bottom processing of stack memory in browser
猜你喜欢
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
Clickhouse table engine
STM32__ 03 - beginner timer
VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
Nifi fast installation and file synchronization
Devexpress GridView add select all columns
Milvus 2.0 质量保障系统详解
RPC核心概念理解
Net standard
Use between nodejs modules
随机推荐
Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
Shell-入门、变量、以及基本的语法
Website_ Collection
[markdown notes]
Solution architect's small bag - 5 types of architecture diagrams
JS to find the character that appears three times in the string
Decimal format decimal / datetime conversion processing
[C#] 彻底搞明白深拷贝
Calculation formula related to tolerance analysis
Wiper component encapsulation
Read a blog, re understand closures and tidy up
matlab如何绘制已知公式的曲线图,Excel怎么绘制函数曲线图像?
PHP高效读大文件处理数据
Bottom processing of stack memory in browser
Simulation of infrared wireless communication based on 51 single chip microcomputer
[problem solving] [show2012] random tree
MySQL master-slave configuration under CentOS
Understanding of RPC core concepts
Getting started with JDBC
Sub database and sub table & shardingsphere