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());
相关推荐
2601_9620725513 小时前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
步步为营DotNet1 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
咸鱼翻身小阿橙1 天前
VS2008 + .NET3.5 环境、加热台TCP通讯场景
tcp/ip·php·.net
tonydf2 天前
DotNet项目接入Copilot SDK简单案例
后端·.net·github copilot
ABprogramming2 天前
Aspire入门指南
c#·.net
User_芊芊君子2 天前
鸿蒙PC适配:Pinta GTK 图像编辑器鸿蒙 PC ArkWeb 适配全记录:从 .NET_GTK4 桌面到 HarmonyOS PC HAP
编辑器·.net·harmonyos
ServBay2 天前
你跟高级 C# 工程师的区别,就是这8个开发技巧
后端·c#·.net
小满Autumn3 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
ceclar1233 天前
C# 的任务并行库(TPL)
开发语言·c#·.net