Quartz.Net_侦听触发器

简述

触发器执行任务时存在数个阶段,利用侦听器可以在对应的阶段执行一些代码

如何侦听

1.实现ITriggerListener接口,并实现其函数,具体说明见代码注释

cs 复制代码
public class DeleteAfterCompleted : ITriggerListener
{
    public string Name => "X";

    // 触发时
    public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
    {
        await Console.Out.WriteLineAsync("TriggerFired");
        await Task.CompletedTask;
    }
    // 错过触发时
    public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
    {
        await Console.Out.WriteLineAsync("TriggerMisfired");
        await Task.CompletedTask;
    }
    // 任务执行前
    public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
    {
        await Console.Out.WriteLineAsync("VetoJobExecution");
        return await Task.FromResult(cancellationToken.IsCancellationRequested);
    }
    // 任务完成后
    public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
    {
        await Console.Out.WriteLineAsync("TriggerComplete");
        var scheduler = await SchedulerGetter.GetSchedulerAsync();
        if (string.IsNullOrEmpty(context.NextFireTimeUtc?.LocalDateTime.ToString()))
        {
            await scheduler.UnscheduleJob(trigger.Key);
            await Console.Out.WriteLineAsync("已删除");
        }
    }
}

2.为调度器添加侦听器

cs 复制代码
public class TriggerListenerGetter
{
    private static readonly DeleteAfterCompleted listener = new();
    public static ITriggerListener GetListener()
    {
        return listener;
    }
}
cs 复制代码
IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();
scheduler.ListenerManager.AddTriggerListener(TriggerListenerGetter.GetListener());
相关推荐
假装我不帅10 小时前
wsl+vscode开发.net项目
ide·vscode·.net
CodeCraft Studio1 天前
国产化PDF处理控件Spire.PDF教程:如何在 C# 中从 HTML 和 PDF 模板生成 PDF
pdf·c#·html·.net·spire.pdf·pdf文档开发·html创建模板pdf
ysdysyn1 天前
.NET 10深度解析:性能革新与开发生态的全新篇章
c#·.net
fs哆哆2 天前
在VB.NET中,有没有 ?.这个运算符
java·开发语言·.net
荔园微风2 天前
微软ML.NET技术详解:从数据科学到生产部署的全栈解决方案
microsoft·.net
荔园微风2 天前
ML.NET机器学习框架基本流程介绍
人工智能·机器学习·.net
InCerry3 天前
为 .NET 10 GC(DATAS)做准备
性能优化·c#·.net·gc
关关长语3 天前
(一) Dotnet使用MCP的Csharp SDK
网络·.net·mcp
喵叔哟3 天前
7. 从0到上线:.NET 8 + ML.NET LTR 智能类目匹配实战--反馈存储与数据治理:MongoDB 设计与运维
运维·mongodb·.net