public static void RepeatUntil(this BackgroundTask task, string expression, DateTimeOffset end)
 {
     task.Expression = expression;
     task.End        = end;
 }
 public static void RepeatIndefinitely(this BackgroundTask task, string expression)
 {
     task.Expression = expression;
 }
Esempio n. 3
0
        private async Task <bool> PerformAsync(BackgroundTask task)
        {
            var handler = CreateHandler(task);

            if (handler == null)
            {
                task.LastError = ErrorStrings.InvalidHandler;
                return(false);
            }

            var hooks = GetOrCreateMethodHooks(handler);

            using var context = ProvisionExecutionContext(_cancel.Token, task.Data);

            _pending.TryAdd(handler, hooks);

            try
            {
                // Before:
                if (hooks.OnBefore != null)
                {
                    await hooks.OnBefore.BeforeAsync(context);
                }

                // Handler:
                if (context.Continue)
                {
                    await hooks.Handler.PerformAsync(context);
                }

                // Success:
                if (context.Successful && hooks.OnSuccess != null)
                {
                    await hooks.OnSuccess.SuccessAsync(context);
                }

                // Failure:
                if (!context.Successful || task.Attempts >= task.MaximumAttempts)
                {
                    if (hooks.OnFailure != null)
                    {
                        await hooks.OnFailure?.FailureAsync(context);
                    }
                }

                // After:
                if (hooks.OnAfter != null)
                {
                    await hooks.OnAfter?.AfterAsync(context);
                }
            }
            catch (OperationCanceledException)
            {
                task.LastError = "Cancelled";
            }
            catch (Exception e)
            {
                task.LastError = e.Message;
                hooks?.OnError?.ErrorAsync(context, e);
            }
            finally
            {
                // Error (passed via context):
                if (task.LastError != null && hooks?.OnError != null && context.Error != null)
                {
                    task.LastError = context.Error.Message;
                    hooks.OnError?.ErrorAsync(context, context.Error);
                }

                _pending.TryRemove(handler, out _);
            }

            return(context.Successful);
        }