C#-Quartz.net CancellationToken
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-Quartz.net CancellationToken,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1870字,纯文字阅读大概需要3分钟。
内容图文
![C#-Quartz.net CancellationToken](/upload/InfoBanner/zyjiaocheng/668/d361106cb4d14f609955ca5719421aab.jpg)
在我的计划程序中,用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行),“中断”方法应用作业执行上下文的取消标记.因此,最好使用图书馆的设施.
内容总结
以上是互联网集市为您收集整理的C#-Quartz.net CancellationToken全部内容,希望文章能够帮你解决C#-Quartz.net CancellationToken所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。