Quartz 多触发器
Quartz 被设计成能够为一个作业注册多个触发器。每个作业可以有一组基准数据,而每个触发器也可以携带自己的一组数据。在作业执行期间,Quartz 会为您合并这些数据,触发器中的数据会覆盖作业中的数据。
我们的示例作业如下:
public class HelloJob : IJob
{
public static readonly JobKey Key = new JobKey("customer-process", "group");
public async Task Execute(IJobExecutionContext context)
{
var customerId = context.MergedJobDataMap.GetString("CustomerId");
var batchSize = context.MergedJobDataMap.GetString("batch-size");
await Console.WriteLineAsync($"CustomerId={customerId} batch-size={batchSize}")
}
}
以下有两个触发器,每个都有自己的数据集,但我们只需要注册一个作业。
public Task DoSomething(IScheduler schedule, CancellationToken ct)
{
var job = JobBuilder.Create<HelloJob>()
.WithIdentity(HelloJob.Key)
.Build();
await schedule.AddJob(job, replace: true, storeNonDurableWhileAwaitingScheduling: true, ct);
// Trigger 1
var jobData1 = new JobDataMap { { "CustomerId", "1" } };
await scheduler.TriggerJob(new JobKey("customer-process", "group"), jobData1, ct);
// Trigger 2
var jobData2 = new JobDataMap { { "CustomerId", "2" } };
await scheduler.TriggerJob(new JobKey("customer-process", "group"), jobData2, ct);
}
当这段代码运行时,您将看到如下输出:
CustomerId=1 batch-size=
CustomerId=2 batch-size=
作业数据与触发器数据
您甚至可以在作业本身上设置一些通用的数据参数。这里我们在作业本身添加了一些作业数据。
public Task DoSomething(IScheduler schedule, CancellationToken ct)
{
var job = JobBuilder.Create<AnExampleJob>()
.WithIdentity(HelloJob.Key)
.UsingJobData("batch-size", "50")
.Build();
await schedule.AddJob(job, replace: true, storeNonDurableWhileAwaitingScheduling: true, ct);
// Trigger 1
var jobData1 = new JobDataMap { { "CustomerId", 1 } };
await scheduler.TriggerJob(HelloJob.Key, jobData1, ct);
// Trigger 2
var jobData2 = new JobDataMap { { "CustomerId", 2 } };
await scheduler.TriggerJob(HelloJob.Key, jobData2, ct);
}
当这段代码运行时,您将看到如下输出:
CustomerId=1 batch-size=50
CustomerId=2 batch-size=50