예제 #1
0
 public void OnPerformed(PerformedContext filterContext)
 {
     if (filterContext.Exception is null || filterContext.ExceptionHandled)
     {
         RemoveFingerprint(filterContext.Connection, filterContext.BackgroundJob.Job);
     }
 }
예제 #2
0
    public void OnPerformed(PerformedContext filterContext)
    {
        // Do your exception handling or validation here
        if (filterContext.Exception == null)
        {
            return;
        }

        using (var connection = _jobStorage.GetConnection())
        {
            var storageConnection = connection as JobStorageConnection;

            if (storageConnection == null)
            {
                return;
            }

            var jobId = filterContext.BackgroundJob.Id
                        // var job = storageConnection.GetJobData(jobId); -- If you want job detail

                        var failedState = new FailedState(filterContext.Exception)
            {
                Reason = "Your Exception Message or filterContext.Exception.Message"
            };

            using (var transaction = connection.GetConnection().CreateWriteTransaction())
            {
                transaction.RemoveFromSet("retries", jobId);          // Remove from retry state
                transaction.RemoveFromSet("schedule", jobId);         // Remove from schedule state
                transaction.SetJobState(jobId, failedState);          // update status with failed state
                transaction.Commit();
            }
        }
    }
 public void OnPerformed(PerformedContext filterContext)
 {
     Logger.InfoFormat("Job `{0}` has been performed", filterContext.BackgroundJob.Id);
     WriteLog(
         $"{ApiConfig.HangfireLogUrl}\\OnPerformed-{(filterContext.BackgroundJob?.Id ?? "0")}-{DateTime.Now:yyyy-MM-dd}.txt",
         $"Job `{ filterContext.BackgroundJob.Id}` has been performed . 时间为:{DateTime.Now:yyyy-MM-dd-HH-mm-ss} \r\n");
 }
예제 #4
0
        public void OnPerformed(PerformedContext context)
        {
            if (context.Items.TryGetValue("App_TransactionScope", out var scope1) &&
                scope1 is TransactionScope transactionScope)
            {
                if (context.Exception != null)
                {
                    // transactionScope.RollBack();
                }
            }
            else
            {
                throw new InvalidOperationException("FilterContext does not contain 'App_TransactionScope' object of TransactionScope type");
            }

            if (context.Items.TryGetValue("App_ServiceScope", out var scope2) &&
                scope2 is IServiceScope serviceScope)
            {
                serviceScope.Dispose();
            }
            else
            {
                throw new InvalidOperationException("FilterContext does not contain 'App_ServiceScope' object of IServiceScope type");
            }
        }
        /// <summary>
        /// 执行完毕
        /// </summary>
        /// <param name="context"></param>
        public void OnPerformed(PerformedContext context)
        {
            var jobname = context.JobId;
            var arg     = string.Join(" , ", context.Job.Args.ToArray());

            Logger.WarnFormat("   执行完毕  Job `{0}` ,  Arg is  `{1}`", jobname, arg);
        }
예제 #6
0
        public void OnPerformed(PerformedContext filterContext)
        {
            if (!filterContext.Items.ContainsKey("DistributedLock"))
            {
                throw new InvalidOperationException("can not found DistributedLock in filterContext");
            }
            //释放系统自带的分布式锁
            var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];

            distributedLock.Dispose();


            //删除设置运行时被设置的参数
            try
            {
                var hashKey = filterContext.GetJobParameter <string>("runtimeKey");
                if (!string.IsNullOrEmpty(hashKey))
                {
                    using (var tran = filterContext.Connection.CreateWriteTransaction())
                    {
                        tran.RemoveHash(hashKey);
                        tran.Commit();
                    }
                }
            }
            catch (Exception)
            {
                //ignore
            }
        }
예제 #7
0
    public void OnPerformed(PerformedContext context)
    {
        // Check that the job completed successfully
        if (!context.Canceled && context.Exception != null)
        {
            // Here you would write to your database.
            // Example with entity framework:
            using (var ctx = new YourDatabaseContext())
            {
                ctx.Something.Add(/**/);
                ctx.SaveChanges();
            }
        }
    }
}
And then apply the filter to the job method:
cs
namespace myAPI
{
   public class WebApiApplication : System.Web.HttpApplication
   {
      protected void Application_Start(
      {
         System.Diagnostics.Debug.WriteLine("Recurring job will be set up.");
         RecurringJob.AddOrUpdate("some-id", () => MyJob(), "*/2 * * * 1-5"); 
      }
 public void OnPerformed(PerformedContext filterContext)
 {
     if (filterContext.Items.TryGetValue(CorrelateActivityKey, out object objActivity) &&
         objActivity is IActivity activity)
     {
         activity.Stop();
     }
 }
예제 #9
0
        public void OnPerformed(PerformedContext filterContext)
        {
            var scope = lifestyle.GetCurrentScope(_container);

            if (scope != null)
            {
                scope.Dispose();
            }
        }
예제 #10
0
        public void OnPerformed(PerformedContext filterContext)
        {
            if (!filterContext.Items.ContainsKey("DistributedLock"))
            {
                throw new InvalidOperationException("can not found DistributedLock in filterContext");
            }

            //删除设置运行时被设置的参数
            try
            {
                if (filterContext.Items.TryGetValue("runtimeKey", out var hashKey))
                {
                    if (!filterContext.Items.ContainsKey("RetryCount"))//执行出错需要retry的时候才会有
                    {
                        //代表是运行期间没有throw 直接删除
                        filterContext.Items.Remove("runtimeKey");
                        var hashKeyStr = hashKey as string;
                        if (!string.IsNullOrEmpty(hashKeyStr))
                        {
                            using (var tran = filterContext.Connection.CreateWriteTransaction())
                            {
                                tran.RemoveHash(hashKeyStr);
                                tran.Commit();
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //ignore
            }

            try
            {
                if (filterContext.Items.TryGetValue("runtimeKey_dic", out var hashDic))
                {
                    if (hashDic is Dictionary <string, string> dic)
                    {
                        foreach (var item in dic)
                        {
                            filterContext.Items.Remove(item.Key);
                        }
                    }
                }
            }
            catch (Exception)
            {
                //ignore
            }


            //释放系统自带的分布式锁
            var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];

            distributedLock.Dispose();
        }
예제 #11
0
        /// <summary>
        /// 执行结束
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnPerformed(PerformedContext filterContext)
        {
            var jobId = buildJobId(filterContext.BackgroundJob);

            if (_jobPerforming.ContainsKey(jobId))
            {
                _jobPerforming.TryRemove(jobId, out DateTime value);
            }
        }
    public void OnPerformed(PerformedContext filterContext)
    {
        if (!filterContext.Items.ContainsKey("DistributedLock"))
        {
            throw new InvalidOperationException("Can not release a distributed lock: it was not acquired.");
        }
        var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];

        distributedLock.Dispose();
    }
        public void OnPerformed(PerformedContext filterContext)
        {
            var id       = filterContext.BackgroundJob.Id;
            var canceled = filterContext.CancellationToken.ShutdownToken.IsCancellationRequested;

            if (filterContext.Exception == null || filterContext.ExceptionHandled || canceled)
            {
                RemoveFingerprint(filterContext.Connection, filterContext.BackgroundJob.Job);
            }
        }
        public void OnPerformed(PerformedContext context)
        {
            if (context.Canceled)
            {
                // Processing was been cancelled by one of the job filters
                // There's nothing to do here, as processing hasn't started
                return;
            }

            ConsoleContext.FromPerformContext(context)?.Expire(_options.ExpireIn);
        }
예제 #15
0
        public void OnPerformed(PerformedContext filterContext)
        {
            if (!filterContext.Items.ContainsKey("DistributedLock"))
            {
                throw new InvalidOperationException("找不到分布式锁,没有为该任务申请分布式锁.");
            }
            //释放分布式锁
            var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];

            distributedLock.Dispose();
        }
예제 #16
0
 public void OnPerformed(PerformedContext filterContext)
 {
     if (filterContext.Exception != null)
     {
         _eventBus.Publish(new BackgroundJobExceptionEvent(
                               "A background job execution is failed on Hangfire. See inner exception for details. Use JobObject to get Hangfire background job object.",
                               filterContext.Exception)
         {
             JobObject = filterContext.BackgroundJob
         });
     }
 }
예제 #17
0
        public void OnPerformed(PerformedContext filterContext)
        {
            if (!filterContext.Items.ContainsKey("DistributedLock"))
            {
                string message = "HangFire can't release a distributed lock: it was not acquired.";
                Logger.Warn(message);
                throw new InvalidOperationException(message);
            }

            var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];

            distributedLock.Dispose();
        }
        public void OnPerformed(PerformedContext filterContext)
        {
            //if (filterContext == null) throw new ArgumentNullException(nameof(filterContext));

            //if (filterContext.Items.ContainsKey("PreviousCulture"))
            //{
            //    SetCurrentCulture((CultureInfo) filterContext.Items["PreviousCulture"]);
            //}
            //if (filterContext.Items.ContainsKey("PreviousUICulture"))
            //{
            //    SetCurrentUICulture((CultureInfo)filterContext.Items["PreviousUICulture"]);
            //}
        }
예제 #19
0
 public void OnPerformed(PerformedContext context)
 {
     // Check that the job completed successfully
     if (!context.Canceled && context.Exception != null)
     {
         // Here you would write to your database.
         // Example with entity framework:
         using (var ctx = new YourDatabaseContext())
         {
             ctx.Something.Add(/**/);
             ctx.SaveChanges();
         }
     }
 }
 public override void OnPerformed(PerformedContext context)
 {
     try
     {
         var result = _lifeCycleHandler.HandleOnPerformed(context).Result;
         if (!result)
         {
             _logger.LogError("Could not handle OnPerformed() for {@arg}", GetWorkArguments(context.BackgroundJob?.Job));
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Error occurred while handling OnPerformed() for {@arg} for {@arg}", GetWorkArguments(context.BackgroundJob?.Job));
     }
 }
        void IServerFilter.OnPerformed(PerformedContext filterContext)
        {
            if (filterContext.Exception is null == false)
            {
                return;
            }

            var jobId      = this.GetJobIdentifier(filterContext.BackgroundJob.Job);
            var connection = JobStorage.Current.GetConnection();

            connection.SetRangeInHash(jobId, new Dictionary <string, string>
            {
                { ParameterName, DateTime.UtcNow.ToString("O") }
            });
        }
예제 #22
0
        public void OnPerformed(PerformedContext filterContext)
        {
            //if an exception of type Exception is thrown, cancel the schedule
            if (filterContext.Exception?.InnerException?.GetType() != typeof(Exception))
            {
                return;
            }
            var recurringJob = filterContext.Connection.GetRecurringJobs()
                               .SingleOrDefault(dto => dto.LastJobId == filterContext.BackgroundJob.Id);

            if (recurringJob != null)
            {
                RecurringJob.RemoveIfExists(recurringJob.Id);
            }
        }
            private Task PerformJobAsync()
            {
                const TaskContinuationOptions options = TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.ExecuteSynchronously;

                try
                {
                    return(_innerPerformer.PerformAsync(_context).ContinueWith(FillPerformedContext, this, options));
                }
                catch (Exception ex)
                {
                    // fill performedContext with exception if failed to create task at all
                    _performedContext = new PerformedContext(_context, null, false, ex);
                    return(Task.FromResult(0));
                }
            }
예제 #24
0
        public void OnPerformed(PerformedContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.Items.ContainsKey("PreviousCulture"))
            {
                Thread.CurrentThread.CurrentCulture = (CultureInfo)filterContext.Items["PreviousCulture"];
            }
            if (filterContext.Items.ContainsKey("PreviousUICulture"))
            {
                Thread.CurrentThread.CurrentUICulture = (CultureInfo)filterContext.Items["PreviousUICulture"];
            }
        }
예제 #25
0
        public void OnPerformed(PerformedContext filterContext)
        {
            //if it's a recurring job, save arguments as they are after the job executed
            if (filterContext.Exception != null)
            {
                return;
            }
            var job          = filterContext.BackgroundJob;
            var recurringJob = filterContext.Connection.GetRecurringJobs()
                               .SingleOrDefault(dto => dto.LastJobId == job.Id);

            if (recurringJob != null)
            {
                new RecurringJobManager().AddOrUpdate(recurringJob.Id, job.Job, recurringJob.Cron);
            }
        }
 public void OnPerformed(PerformedContext filterContext)
 {
     Logger.InfoFormat("Starting to perform job `{0}`", filterContext.BackgroundJob.Id);
     try
     {
         if (filterContext.Exception == null || filterContext.ExceptionHandled)
         {
             RemoveFingerprint(filterContext.Connection, filterContext.BackgroundJob.Job);
         }
     }
     catch (Exception)
     {
         // Unhandled exceptions can cause an endless loop.
         // Therefore, catch and ignore them all.
     }
 }
예제 #27
0
        public void OnPerformed(PerformedContext context)
        {
            var scope = GlobalTracer.Instance.ScopeManager.Active;

            if (scope == null)
            {
                return;
            }

            if (context.Exception != null)
            {
                SetSpanException(scope.Span, context.Exception);
            }

            scope.Dispose();
        }
예제 #28
0
        /// <summary>
        /// Action: OnPerformed
        /// Description: It is the final filter to used for updating sync status to 2.
        /// Sync status 2 means completed.
        /// </summary>
        /// <param name="context"></param>
        void IServerFilter.OnPerformed(PerformedContext context)
        {
            if (context.Canceled == false && context.Exception == null)
            {
                Console.WriteLine(string.Format("Job `{0}` has been performed", context.BackgroundJob?.Id));
                var ccid        = context.BackgroundJob.Job.Args.ElementAt(2) as string;
                int connectorId = (int)context.BackgroundJob.Job.Args.ElementAt(1);
                if (!string.IsNullOrEmpty(ccid) && connectorId > 0)
                {
                    if (GC.GetTotalMemory(false) >= 67108864)
                    {
                        Console.WriteLine($"GC.Generation: 2, max allocated memory: {GC.GetTotalMemory(false)}");
                        GC.Collect(2);
                        GC.WaitForPendingFinalizers();
                        GC.Collect(2);
                        Console.WriteLine($"Max allocated memory after GC.Collect: {GC.GetTotalMemory(false)}");
                    }

                    if (GC.GetTotalMemory(false) >= 33554432)
                    {
                        Console.WriteLine($"GC.Generation: 1, max allocated memory: {GC.GetTotalMemory(false)}");
                        GC.Collect(1);
                        GC.WaitForPendingFinalizers();
                        GC.Collect(1);
                        Console.WriteLine($"Max allocated memory after GC.Collect: {GC.GetTotalMemory(false)}");
                    }

                    if (GC.GetTotalMemory(false) >= 20971520)
                    {
                        Console.WriteLine($"GC.Generation: 0, max allocated memory: {GC.GetTotalMemory(false)}");
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        GC.Collect();
                        Console.WriteLine($"Max allocated memory after GC.Collect: {GC.GetTotalMemory(false)}");
                    }

                    //set sync status to completed{2}
                    var connectorLogs = new ConnectorLogs()
                    {
                        sync_ended_at = DateTime.UtcNow,
                        sync_logs     = new List <string>()
                    };

                    SyncRepository.UpdateSyncInfo(id: connectorId, ccid: ccid, status: 2, connectorLogs: connectorLogs);
                }
            }
        }
        public virtual void OnPerformed(PerformedContext filterContext)
        {
            if (!filterContext.Items.ContainsKey("DistributedLock"))
            {
                throw new InvalidOperationException("Can not release a distributed lock: it was not acquired.");
            }

            // be sure to dispose the distributed lock when the job is done
            var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];

            distributedLock.Dispose();

            // and also release the lock from the local lock cache
            var distributedLockName = (string)filterContext.Items["DistributedLockName"];

            locallyAcquiredLocks.TryRemove(distributedLockName, out _);
        }
예제 #30
0
        public void OnPerformed(PerformedContext filterContext)
        {
            //删除设置运行时被设置的参数
            try
            {
                if (filterContext.Items.TryGetValue("runtimeKey", out var hashKey))
                {
                    if (!filterContext.Items.ContainsKey("RetryCount"))//执行出错需要retry的时候才会有
                    {
                        //代表是运行期间没有throw 直接删除
                        filterContext.Items.Remove("runtimeKey");
                        var hashKeyStr = hashKey as string;
                        if (!string.IsNullOrEmpty(hashKeyStr))
                        {
                            using (var tran = filterContext.Connection.CreateWriteTransaction())
                            {
                                tran.RemoveHash(hashKeyStr);
                                tran.Commit();
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //ignore
            }

            try
            {
                if (filterContext.Items.TryGetValue("runtimeKey_dic", out var hashDic))
                {
                    if (hashDic is Dictionary <string, string> dic)
                    {
                        foreach (var item in dic)
                        {
                            filterContext.Items.Remove(item.Key);
                        }
                    }
                }
            }
            catch (Exception)
            {
                //ignore
            }
        }
예제 #31
0
        public void OnPerformed(PerformedContext filterContext)
        {
            Assert.NotNull(filterContext);

            _results.Add(String.Format("{0}::{1}", _name, "OnPerformed")
                + (filterContext.Canceled ? " (with the canceled flag set)" : null));

            if (_handlesException)
            {
                filterContext.ExceptionHandled = true;
            }
        }