Hangfire 服務器喚醒後,阻止執行錯過的做業

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

 /// <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)
        {
        }
    }

 

使用方式:github

啓動時添加過濾器
GlobalJobFilters.Filters.Add(new NoMissedRunsAttribute());async

在執行的job上spa

        /// <summary>
        ///     執行同步操做
        /// </summary>
        //[UnitOfWork]
        [NoMissedRunsAttribute]
        public virtual async Task Execute()
        {
		.....
	}
相關文章
相關標籤/搜索