Quartz.Net_侦听触发器

简述

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

如何侦听

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

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.为调度器添加侦听器

public class TriggerListenerGetter
{
    private static readonly DeleteAfterCompleted listener = new();
    public static ITriggerListener GetListener()
    {
        return listener;
    }
}
IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();
scheduler.ListenerManager.AddTriggerListener(TriggerListenerGetter.GetListener());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值