Hangfire 服务器唤醒后,阻止执行错过的作业

原文:https://github.com/HangfireIO/Hangfire/issues/620

 /// <summary>
    /// 错过不执行
    /// </summary>
    public class NoMissedRunsAttribute : JobFilterAttribute, IClientFilter
    {
        /// <summary>
        /// 设置逾期时间
        /// </summary>
        public TimeSpan MaxDelay { get; set; } = TimeSpan.FromMinutes(15);

        public void OnCreating(CreatingContext context)
        {
            if (context.Parameters.TryGetValue("RecurringJobId", out var recurringJobId) &&
                context.InitialState?.Reason == "Triggered by recurring job scheduler")
            {
                // the job being created looks like a recurring job instance,
                // and triggered by a scheduler (i.e. not manually) at that.

                var recurringJob = context.Connection.GetAllEntriesFromHash($"recurring-job:{recurringJobId}");

                if (recurringJob != null && recurringJob.TryGetValue("NextExecution", out var nextExecution))
                {
                    // the next execution time of a recurring job is updated AFTER the job instance creation,
                    // so at the moment it still contains the scheduled execution time from the previous run.

                    var scheduledTime = JobHelper.DeserializeDateTime(nextExecution);

                    if (DateTime.UtcNow > scheduledTime + MaxDelay)
                    {
                        // the job is created way later than expected
                        context.Canceled = true;
                    }
                }
            }
        }

        public void OnCreated(CreatedContext context)
        {
        }
    }

 

使用方式:

启动时添加过滤器
GlobalJobFilters.Filters.Add(new NoMissedRunsAttribute());

在执行的job上

        /// <summary>
        ///     执行同步操作
        /// </summary>
        //[UnitOfWork]
        [NoMissedRunsAttribute]
        public virtual async Task Execute()
        {
		.....
	}

转载于:https://www.cnblogs.com/hongshao/p/11369515.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值