在用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并抛出异常。但不起作用。
发布于 2018-01-24 18:09:47
根据文档,您应该使用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,石英将终止作业。
编辑
根据源代码 (第2151行),Interrupt方法应用作业执行上下文的取消令牌。因此,最好是利用图书馆的设施。
发布于 2018-01-25 11:32:37
以下是Github的单元测试:https://github.com/quartznet/quartznet/blob/master/src/Quartz.Tests.Unit/InterrubtableJobTest.cs
我试着用同样的方式实现取消,但对我来说也不管用。
@Stormcloak我必须检查取消请求,因为我想为作业执行一些中止操作,例如将状态数据写入数据库。
编辑:
所以,经过多次测试和实现。我让它跑了。
这里有一些伪代码:
this.scheduler = await StdSchedulerFactory.GetDefaultScheduler();
this.tokenSource = new CancellationTokenSource();
this.token = tokenSource.Token;
// Start scheduler.
await this.scheduler.Start(token);
// add some jobs here
// ...
// cancel running jobs.
IReadOnlyCollection<IJobExecutionContext> jobs = await this.scheduler.GetCurrentlyExecutingJobs();
foreach (IJobExecutionContext context in jobs)
{
result = await this.scheduler.Interrupt(context.JobDetail.Key, this.token);
}
await this.scheduler.Shutdown(true);因此,现在可以在执行方法中使用CancellationToken。
https://stackoverflow.com/questions/48428141
复制相似问题