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());
相关推荐
wwyyxx261 天前
Linux 下 .NET 程序 CPU 异常占用排查记录
linux·.net·调试
回忆2012初秋1 天前
.NET 时序数据操作实战:Apache IoTDB连接与 CRUD 完全指南
.net·apache·iotdb
回忆2012初秋1 天前
.NET 实战:Redis 缓存穿透、击穿与雪崩的原理剖析与解决方案
redis·缓存·.net
武藤一雄2 天前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
旡心-小小康2 天前
.NET WebSocket Socket
websocket·网络协议·.net
wenha3 天前
踩坑记录:UTF-8、UTF-8-BOM 与 GB2312 读取的乱码真相
utf-8·.net·编码·utf-8-bom
江沉晚呤时3 天前
C# 整型溢出处理机制:checked 与 unchecked 上下文解析
c#·.net
余衫马3 天前
在 Windows 服务中托管 ASP.NET Core Web API (.net6)
运维·windows·后端·asp.net·.net
步步为营DotNet3 天前
LM-Kit.NET:.NET 生态一站式本地 AI 开发平台
人工智能·.net
步步为营DotNet3 天前
.NET 实战 LlamaSharp:本地运行开源大模型
.net