编程语言
首页 > 编程语言> > C#-Quartz.net CancellationToken

C#-Quartz.net CancellationToken

作者:互联网

在我的计划程序中,用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();

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

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

我希望在触发tokenSource.Cancel()时,作业将输入if并引发Exception.但这是行不通的.

解决方法:

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

应用调度程序.在执行作业后中断,石英将终止作业.

编辑

根据source code(第2151行),“中断”方法应用作业执行上下文的取消标记.因此,最好使用图书馆的设施.

标签:quartz-net,scheduler,quartz-scheduler,c,net
来源: https://codeday.me/bug/20191110/2013428.html