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());
相关推荐
玩泥巴的4 小时前
.NET驾驭Word之力:基于规则自动生成及排版Word文档
c#·word·.net·com互操作
专注VB编程开发20年4 小时前
VB.NET多线程排序算法实现:LINQ与正则表达式方法
排序算法·.net·linq
EQ-雪梨蛋花汤9 小时前
【踩坑记录】从“正在还原所需的工具包”说起:一次 .NET 工程包还原失败的完整排查实录
.net
喵叔哟11 小时前
63.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--预算告警
运维·微服务·.net
专注VB编程开发20年11 小时前
VB.NET2003和VB2008可以导入VB6项目
.net·vb.net·vb6·vb2008
喵叔哟12 小时前
62.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--自训练ML模型
微服务·架构·.net
追逐时光者21 小时前
将 EasySQLite 解决方案文件格式从 .sln 升级为更简洁的 .slnx
后端·.net
专注VB编程开发20年1 天前
C#,VB.NET数组去重复,提取键名和重复键和非重复键
c#·.net·linq·取唯一键·去重复·重复数量
Full Stack Developme1 天前
java.net 包详解
java·python·.net
假装我不帅2 天前
wsl+vscode开发.net项目
ide·vscode·.net