luk*_*e88 5 .net c# scheduler quartz-scheduler quartz.net
在我的计划程序中,使用quartz.net v3实现,我正在尝试测试取消令牌的行为:
....
IScheduler scheduler = await factory.GetScheduler();
....
var tokenSource = new CancellationTokenSource();
CancellationToken ct = tokenSource.Token;
// Start scheduler
await scheduler.Start(ct);
// some sleep
await Task.Delay(TimeSpan.FromSeconds(60));
// communicate cancellation
tokenSource.Cancel();
Run Code Online (Sandbox Code Playgroud)
我有一个无限运行的测试作业,并在Execute方法中检查取消令牌:
public async Task Execute(IJobExecutionContext context)
{
while (true)
{
if (context.CancellationToken.IsCancellationRequested)
{
context.CancellationToken.ThrowIfCancellationRequested();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望当tokenSource.Cancel()被解雇时,作业将输入if并引发Exception。但这是行不通的。
根据文档,您应该使用Interruptmethod 取消Quartz作业。
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
var scheduler = await factory.GetScheduler();
await scheduler.Start();
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("myJob", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithRepeatCount(1)
.WithIntervalInSeconds(40))
.Build();
await scheduler.ScheduleJob(job, trigger);
//Configure the cancellation of the schedule job with jobkey
await Task.Delay(TimeSpan.FromSeconds(1));
await scheduler.Interrupt(job.Key);
Run Code Online (Sandbox Code Playgroud)
预定作业班;
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
while (true)
{
if (context.CancellationToken.IsCancellationRequested)
{
context.CancellationToken.ThrowIfCancellationRequested();
// After interrupt the job, the cancellation request activated
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
scheduler.Interrupt在作业执行后申请,石英将终止作业。
编辑
根据源代码(第 2151 行),该Interrupt方法应用作业执行上下文的取消标记。因此,最好使用图书馆的设施。