gpt4 book ai didi

c# - Quartz.net 取消 token

转载 作者:行者123 更新时间:2023-12-02 02:28:07 25 4
gpt4 key购买 nike

在我的调度程序中,使用quartz.net v3 实现,我正在尝试测试取消 token 的行为:

....
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();

我有一个无限运行的测试作业,并在 Execute 方法中检查取消 token :

public async Task Execute(IJobExecutionContext context)
{
while (true)
{
if (context.CancellationToken.IsCancellationRequested)
{
context.CancellationToken.ThrowIfCancellationRequested();
}
}
}

我希望当 tokenSource.Cancel() 被触发时,作业将进入 if 并抛出异常。但它不起作用。

最佳答案

根据documentation ,您应该使用Interrupt方法来取消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);

预定的工作类别;

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
}
}
}
}

在作业执行后应用scheduler.Interrupt,quartz将终止作业。

编辑

根据source code (第 2151 行),Interrupt 方法应用作业执行上下文的取消标记。所以,最好利用图书馆的设施。

关于c# - Quartz.net 取消 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48428141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com