Beispiel #1
0
 public void Run <TJobArgument>(TJobArgument argument)
 {
     foreach (var job in GetJobs <TJobArgument>())
     {
         _jobClient.Create(() => job.Execute(argument), new EnqueuedState());
     }
 }
Beispiel #2
0
        private string CreateSubatomInternal([NotNull, InstantHandle] Expression <Func <Task> > action, IState nextState, JobContinuationOptions continuationOptions)
        {
            var jobId = _client.Create(Job.FromExpression(action), new SubAtomCreatedState(_atomId, nextState, continuationOptions));

            _createdSubAtoms.Add(jobId, nextState);

            return(jobId);
        }
        public async Task BackgroundJobCreateAsync(string targetTypeName, string targetMethodName, string queue = EnqueuedState.DefaultQueue)
        {
            var job = await GetJobAsync(targetTypeName, targetMethodName);

            if (job == null)
            {
                return;
            }
            _backgroundJobClient.Create(job, new EnqueuedState(queue));
        }
        public string ProcessTask(TaskInpuModel inputModel)
        {
            var state = new EnqueuedState(JobQueues.Task);
            var jobId = jobClient.Create <ITaskJob>(job => job.Run(inputModel, null), state);

            state = new EnqueuedState(JobQueues.Notify);
            jobId = jobClient.ContinueWith <INotifyJob>(jobId, job => job.Notify(inputModel, null), state);

            return(jobId);
        }
Beispiel #5
0
        private static void CreateStartUpJob(JobInfo jobInfo, IBackgroundJobClient client)
        {
            var taskType       = Type.GetType(jobInfo.Type, AssemblyResolver, null);
            var taskParameters = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(jobInfo.Paramters), taskType) as ITaskParameters;

            client.Create(CreateJob(taskParameters), new EnqueuedState(taskParameters.Queue));
        }
        public override Task DispatchPostCommitAsync(IDomainEvent domainEvent)
        {
            var domainEventMessage = new DomainEventMessage(_serverSettings.ServerName, domainEvent);

            try
            {
                var job   = Job.FromExpression <IDomainEventsMediator>(m => m.HandlePostCommitDispatchAsync(domainEventMessage));
                var queue = new EnqueuedState(_serverSettings.ServerName);
                _backgroundJobClient.Create(job, queue);
            }
            catch
            {
                //Log Hangfire Post commit event Background enqueue failed
            }

            return(Task.CompletedTask);
        }
Beispiel #7
0
        public static string CreateJobAggregate(this IBackgroundJobClient client, Action <IJobAggregateBuilder> action)
        {
            var jodId   = client.Create(() => Aggregation(), new WaitingState());
            var builder = new JobAggregateBuilder(jodId, client, JobStorage.Current);

            action(builder);

            return(jodId);
        }
        /// <summary>
        /// Creates a background job based on a specified instance method
        /// call expression and places it into its actual queue.
        /// Please, see the <see cref="QueueAttribute"/> to learn how to
        /// place the job on a non-default queue.
        /// </summary>
        ///
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Instance method call expression that will be marshalled to the Server.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Enqueue <T>(this IBackgroundJobClient client, Expression <Action <T> > methodCall)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(client.Create(methodCall, new EnqueuedState()));
        }
Beispiel #9
0
        /// <summary>
        /// Creates a background job based on a specified static method
        /// call expression and places it into its actual queue.
        /// Please, see the <see cref="QueueAttribute"/> to learn how to
        /// place the job on a non-default queue.
        /// </summary>
        ///
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Static method call expression that will be marshalled to the Server.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Enqueue([NotNull] this IBackgroundJobClient client, [InstantHandle] Expression <Action> methodCall)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(client.Create(methodCall, new EnqueuedState()));
        }
        /// <summary>
        /// Creates a new background job based on a specified instance method
        /// call expression and schedules it to be enqueued after a given delay.
        /// </summary>
        ///
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Instance method call expression that will be marshalled to the Server.</param>
        /// <param name="delay">Delay, after which the job will be enqueued.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Schedule <T>(this IBackgroundJobClient client, Expression <Action <T> > methodCall, TimeSpan delay)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(client.Create(methodCall, new ScheduledState(delay)));
        }
Beispiel #11
0
        /// <inheritdoc />
        public async Task Process(ScanQueueMessage message)
        {
            _logger.LogInformation(
                $"Starting scan of {message.Uri} via backend {_backend.Id} from {message.Id}");

            var cancellationTokenSource = new CancellationTokenSource(
                TimeSpan.FromSeconds(_configuration.GetValue <int>("MAX_SCANNING_TIME")));

            var cancellationToken = cancellationTokenSource.Token;

            var result = new ScanResultMessage
            {
                Status = ScanResultStatus.Queued
            };

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                result.Threats = await _backend.ScanAsync(message.Uri, cancellationToken);

                result.Status = ScanResultStatus.Succeeded;

                _logger.LogInformation(
                    $"Backend {_backend.Id} completed a scan of {message.Id} " +
                    $"with result '{string.Join(", ", result.Threats)}'");
            }
            catch (Exception exception)
            {
                result.Status = ScanResultStatus.Failed;

                _logger.LogError(
                    exception, "Scanning failed with exception");
            }
            finally
            {
                stopwatch.Stop();
            }

            result.Duration = stopwatch.ElapsedMilliseconds / 1000;

            try
            {
                _logger.LogInformation(
                    $"Sending scan results with status {result.Status}");

                _jobClient.Create <IScanResultJob>(
                    x => x.Report(message.Id, _backend.Id, result),
                    new EnqueuedState("default"));
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Failed to send scan results");
            }
        }
Beispiel #12
0
 public AtomBuilder(string name, JobStorage jobStorage, IBackgroundJobClient client, Action <IAtomBuilder> buildAtom, IState?initialState = null)
 {
     _client          = client;
     _atomId          = _client.Create(() => Atom.Running(name), new AtomCreatingState());
     _initialState    = initialState ?? new AtomRunningState(_atomId);
     _buildAtom       = buildAtom;
     _jobStorage      = jobStorage;
     _createdSubAtoms = new Dictionary <string, IState>();
 }
Beispiel #13
0
        private void TryScheduleJob(IStorageConnection connection, string recurringJobId, Dictionary <string, string> recurringJob)
        {
            var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]);
            var job           = serializedJob.Deserialize();
            var cron          = recurringJob["Cron"];
            var parts         = cron.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            var cronSchedule  = CrontabSchedule.Parse(cron, new CrontabSchedule.ParseOptions {
                IncludingSeconds = (parts.Length >= 6)
            });

            try
            {
                var timeZone = recurringJob.ContainsKey("TimeZoneId")
                ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"])
                : TimeZoneInfo.Utc;

                var instant = _instantFactory.GetInstant(cronSchedule, timeZone);

                var lastExecutionTime = recurringJob.ContainsKey("LastExecution")
                    ? JobHelper.DeserializeDateTime(recurringJob["LastExecution"])
                    : (DateTime?)null;

                var changedFields = new Dictionary <string, string>();

                if (instant.GetNextInstants(lastExecutionTime).Any())
                {
                    var state = new EnqueuedState {
                        Reason = "Triggered by recurring job scheduler"
                    };
                    var jobId = _client.Create(job, state);

                    if (String.IsNullOrEmpty(jobId))
                    {
                        Logger.DebugFormat(
                            "Recurring job '{0}' execution at '{1}' has been canceled.",
                            recurringJobId,
                            instant.NowInstant);
                    }

                    changedFields.Add("LastExecution", JobHelper.SerializeDateTime(instant.NowInstant));
                    changedFields.Add("LastJobId", jobId ?? String.Empty);
                }

                changedFields.Add("NextExecution", JobHelper.SerializeDateTime(instant.NextInstant));

                connection.SetRangeInHash(
                    String.Format("recurring-job:{0}", recurringJobId),
                    changedFields);
            }
            catch (TimeZoneNotFoundException ex)
            {
                Logger.ErrorException(
                    String.Format("Recurring job '{0}' was not triggered: {1}.", recurringJobId, ex.Message),
                    ex);
            }
        }
Beispiel #14
0
        public string ScheduleJob(enSuspendOption suspendOption, string suspendOptionValue, Dictionary <string, StringBuilder> values)
        {
            var suspensionDate = DateTime.Now;
            var resumptionDate = CalculateResumptionDate(suspensionDate, suspendOption, suspendOptionValue);
            var state          = new ScheduledState(resumptionDate.ToUniversalTime());

            var jobId = _client.Create(() => ResumeWorkflow(values, null), state);

            return(jobId);
        }
Beispiel #15
0
        protected string CreateSubatomInternal(
            Job job,
            IState nextState,
            JobContinuationOptions continuationOptions)
        {
            var jobId = _client.Create(job, new SubAtomCreatedState(_atomId, nextState, continuationOptions));

            _createdSubAtoms.Add(jobId, nextState);
            return(jobId);
        }
Beispiel #16
0
        /// <summary>
        /// Creates a background job based on a specified lambda expression
        /// and places it into its actual queue.
        /// Please, see the <see cref="QueueAttribute"/> to learn how to
        /// place the job on a non-default queue.
        /// </summary>
        ///
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Static method call expression that will be marshalled to the Server.</param>
        /// <param name="queueName">The name of the queue to place the job in. This value overrides <see cref="QueueAttribute"/>.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Enqueue(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Func <Task> > methodCall,
            string queueName = null)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (queueName != null)
            {
                return(client.Create(methodCall, new EnqueuedState(queueName)));
            }

            var job = Job.FromExpression(methodCall);

            return(client.Create(job, new EnqueuedState(job.QueueName)));
        }
Beispiel #17
0
        public string Enqueue <T>(Expression <Action <T> > methodCall, DateTime?executionDate = null)
        {
            if (methodCall == null)
            {
                throw new ArgumentNullException(nameof(methodCall));
            }

            IState state = executionDate.HasValue ? (IState) new ScheduledState(executionDate.Value) : new EnqueuedState();

            return(_client.Create(methodCall, state));
        }
Beispiel #18
0
        /// <summary>
        /// Creates a new background job based on a specified instance method
        /// call expression and schedules it to be enqueued after a given delay.
        /// </summary>
        ///
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Instance method call expression that will be marshalled to the Server.</param>
        /// <param name="delay">Delay, after which the job will be enqueued.</param>
        /// <param name="queueName">The name of the queue to place the job in. This value overrides <see cref="QueueAttribute"/>.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Schedule <T>(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Action <T> > methodCall,
            TimeSpan delay,
            string queueName = null)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (queueName != null)
            {
                return(client.Create(methodCall, new ScheduledState(delay, queueName)));
            }

            var job = Job.FromExpression(methodCall);

            return(client.Create(job, new ScheduledState(delay, job.QueueName)));
        }
Beispiel #19
0
        public void SendScheduleReport_Test()
        {
            // Arrange
            var jobId = _hotelReportService.SendScheduleReport(DateTime.Now.AddMinutes(1), "*****@*****.**");

            _client.Create(It.Is <Job>(job => job
                                       .Method
                                       .Name == "SendReportByEmailAsync" && job
                                       .Args[0]
                                       .ToString() == jobId), It.IsAny <EnqueuedState>());
        }
Beispiel #20
0
        /// <summary>
        /// Creates a new background job based on a specified lambda expression and schedules
        /// it to be enqueued at the specified moment.
        /// </summary>
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Method call expression that will be marshalled to the Server.</param>
        /// <param name="enqueueAt">Moment at which the job will be enqueued.</param>
        /// <param name="queueName">The name of the queue to place the job in. This value overrides <see cref="QueueAttribute"/>.</param>
        /// <returns>Unique identifier of a created job.</returns>
        public static string Schedule <T>(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Func <T, Task> > methodCall,
            DateTimeOffset enqueueAt,
            string queueName = null)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (queueName != null)
            {
                return(client.Create(methodCall, new ScheduledState(enqueueAt.UtcDateTime, queueName)));
            }

            var job = Job.FromExpression(methodCall);

            return(client.Create(methodCall, new ScheduledState(enqueueAt.UtcDateTime, job.QueueName)));
        }
        public void RunGeneratorJob(JobType jobType)
        {
            int batch = BatchIdGenerator.Instance.GetNext();

            for (int i = 0; i < 10_000; i++)
            {
                _client.Create <SimpleJob>(x => x.RunWorkerJob(i, batch, jobType), new EnqueuedState {
                    Queue = "worker-queue"
                });
            }
        }
Beispiel #22
0
        /// <summary>
        /// Creates a background job based on a specified lambda expression
        /// and places it into its actual queue.
        /// Please, see the <see cref="QueueAttribute"/> to learn how to
        /// place the job on a non-default queue.
        /// </summary>
        ///
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Instance method call expression that will be marshalled to the Server.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Enqueue <T>(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Func <T, Task> > methodCall)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.Create(methodCall, new EnqueuedState()));
        }
Beispiel #23
0
        /// <summary>
        /// Creates a new background job based on a specified instance method in a given state.
        /// </summary>
        ///
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Instance method call expression that will be marshalled to the Server.</param>
        /// <param name="state">Initial state of a job.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Create <T>(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Func <T, Task> > methodCall,
            [NotNull] IState state)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.Create(Job.FromExpression(methodCall), state));
        }
Beispiel #24
0
        /// <summary>
        /// Creates a new background job based on a specified lambda expression and schedules
        /// it to be enqueued at the specified moment.
        /// </summary>
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Method call expression that will be marshalled to the Server.</param>
        /// <param name="enqueueAt">Moment at which the job will be enqueued.</param>
        /// <returns>Unique identifier of a created job.</returns>
        public static string Schedule <T>(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Action <T> > methodCall,
            DateTimeOffset enqueueAt)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.Create(methodCall, new ScheduledState(enqueueAt.UtcDateTime)));
        }
Beispiel #25
0
        /// <summary>
        /// Creates a new background job based on a specified instance method call expression and schedules it to be enqueued after a given delay.
        /// 基于指定的实例方法调用表达式创建一个新的后台作业,并将其安排在给定的延迟后排队。
        /// </summary>
        ///
        /// <typeparam name="T">
        /// Type whose method will be invoked during job processing.
        /// 类型,其方法将在作业处理期间调用。
        /// </typeparam>
        /// <param name="client">
        /// A job client instance.
        /// 作业客户端实例。
        /// </param>
        /// <param name="methodCall">
        /// Instance method call expression that will be marshalled to the Server.
        /// 将编组到服务器的实例方法调用表达式。
        /// </param>
        /// <param name="delay">
        /// Delay, after which the job will be enqueued.
        /// 延迟,在此之后作业将进入队列。
        /// </param>
        /// <returns>
        /// Unique identifier of the created job.
        /// 所创建作业的唯一标识符。
        /// </returns>
        public static string Schedule <T>(
            [NotNull] this IBackgroundJobClient client,
            [NotNull, InstantHandle] Expression <Action <T> > methodCall,
            TimeSpan delay)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.Create(methodCall, new ScheduledState(delay)));
        }
        /// <summary>
        /// Creates a new background job based on a specified method call expression
        /// and schedules it to be enqueued at the specified moment of time.
        /// </summary>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Method call expression that will be marshalled to the Server.</param>
        /// <param name="enqueueAt">Moment of time at which the job will be enqueued.</param>
        /// <returns>Unique identifier or a created job.</returns>
        public static string Schedule(
            [NotNull] this IBackgroundJobClient client,
            Expression <Action> methodCall,
            DateTimeOffset enqueueAt)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(client.Create(methodCall, new ScheduledState(enqueueAt.UtcDateTime)));
        }
        /// <summary>
        /// Creates a new background job based on a specified instance method
        /// within a given state.
        /// </summary>
        ///
        /// <typeparam name="T">Type whose method will be invoked during job processing.</typeparam>
        /// <param name="client">A job client instance.</param>
        /// <param name="methodCall">Instance method call expression that will be marshalled to the Server.</param>
        /// <param name="state">Initial state of a job.</param>
        /// <returns>Unique identifier of the created job.</returns>
        public static string Create <T>(
            this IBackgroundJobClient client,
            Expression <Action <T> > methodCall,
            IState state)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(client.Create(Job.FromExpression(methodCall), state));
        }
Beispiel #28
0
        public string EnqueueWithHighPriority <T>(Expression <Action <T> > methodCall, string originalJobId = null)
        {
            var state    = new EnqueuedState(HangfireConstants.HighPriorityQueue);
            var newJobId = _backgroundJobClient.Create(methodCall, state);

            if (originalJobId != null)
            {
                _backgroundJobClient.Delete(originalJobId);
            }

            return(newJobId);
        }
        public static string Create(
            [NotNull] this IBackgroundJobClient client,
            [NotNull] string queueName,
            [NotNull, InstantHandle] Expression <Action> methodCall,
            [NotNull] IState state)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.Create(queueName, Job.FromExpression(methodCall), state));
        }
Beispiel #30
0
        public override Task PublishPostCommitAsync(DomainEvent domainEvent, CancellationToken cancellationToken = default)
        {
            var handlerTypes = DomainEventSubscriptionsManager.GetHandlersForEvent(domainEvent).ToList();

            //Only persist domainEvent to Hangfire if it has > 0 handlers.
            if (handlerTypes.Count > 0)
            {
                var eventName = DomainEventSubscriptionsManager.GetEventKey(domainEvent.GetType());
                var payload   = JsonConvert.SerializeObject(domainEvent);

                try
                {
                    var job   = Job.FromExpression <IDomainEventBus>(m => m.ProcessPostCommitAsync(eventName, payload));
                    var queue = new EnqueuedState(_options.ServerName);
                    _backgroundJobClient.Create(job, queue);
                }
                catch
                {
                    //Log Hangfire Post commit event Background enqueue failed
                }
            }

            return(Task.CompletedTask);
        }