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());
相关推荐
步、步、为营11 小时前
.net consul服务注册与发现
.net·consul
步、步、为营11 小时前
.net Avalonia应用程序生命周期
.net
xk_hypothesis11 小时前
.NET WinForm图像识别二维码/条形码并读取其中内容
.net
追逐时光者18 小时前
一款 .NET 开源、免费的适用于 Windows 下 PC 版微信/QQ/TIM的防撤回补丁(我已经看到了,撤回也没用了)!!
后端·.net
Kookoos2 天前
健康检查:在 .NET 微服务模板中优雅配置 Health Checks
微服务·架构·.net·abp vnext
追逐时光者2 天前
C#/.NET/.NET Core技术前沿周刊 | 第 40 期(2025年5.26-5.31)
后端·.net
ArabySide2 天前
【EF Core】 EF Core 批量操作的进化之路——从传统变更跟踪到无跟踪更新
数据库·.net·efcore
有梦想的咕噜3 天前
.NET 查找 DLL 的路径顺序
.net
江沉晚呤时3 天前
深入解析 Dotnet-Boxed.Framework:提升 .NET 开发效率的利器
深度学习·c#·.net·.netcore
步、步、为营3 天前
.net Avalonia 在centos部署
linux·centos·.net