/// <inheritdoc />
        public Task <string> EnqueueChildAsync(BackgroundTaskEnvelope task, string parentId, BackgroundTaskContinuationOptions continuationOptions)
        {
            var hangfireOptions = continuationOptions == BackgroundTaskContinuationOptions.OnlyOnSucceededState
                ? JobContinuationOptions.OnlyOnSucceededState
                : JobContinuationOptions.OnAnyFinishedState;

            return(Task.FromResult(this.CreateCore(
                                       task,
                                       queue => new AwaitingState(parentId, new EnqueuedState(queue), hangfireOptions))));
        }
        private string GetQueueForTask(BackgroundTaskEnvelope envelope)
        {
            var taskType = envelope.Task.GetType();

            if (!_taskToQueue.TryGetValue(taskType, out var queue))
            {
                var queueAttribute = taskType.GetAttributesIncludingInterface <QueueAttribute>().SingleOrDefault();
                queue = queueAttribute == null ? EnqueuedState.DefaultQueue : queueAttribute.Queue;

                _taskToQueue[taskType] = queue;
            }

            return(queue);
        }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public Task UpdateAsync(IEnumerable <RecurringTaskScheduleDto> current)
        {
            var existingJobs        = JobStorage.Current.GetConnection().GetRecurringJobs();
            var currentAsDictionary = current.ToDictionary(k => k.Id, v => v);

            // Finds jobs that exist in Hangfire but _do not_ exist in current list (with special case of
            // the system scheduler)
            var jobsToDelete = existingJobs
                               .Where(jk => !currentAsDictionary.ContainsKey(jk.Id) && jk.Id != SchedulerJobId)
                               .ToList();

            this._logger.LogInformation("Deleting old jobs that no longer exist");

            foreach (var j in jobsToDelete)
            {
                this._recurringJobManager.RemoveIfExists(j.Id);
            }

            this._logger.LogInformation("Scheduling (add or update) current jobs");

            foreach (var kvp in currentAsDictionary)
            {
                var schedule = kvp.Value;

                var envelope = new BackgroundTaskEnvelope(schedule.Schedule.BackgroundTask);

                var job = Job.FromExpression <HangfireTaskExecutor>(
                    e => e.Execute(
                        new HangfireBackgroundTaskWrapper(envelope),
                        null,
                        CancellationToken.None));

                this._recurringJobManager.AddOrUpdate(
                    schedule.Id,
                    job,
                    schedule.Schedule.CronExpression,
                    schedule.Schedule.TimeZone);

                this._logger.LogDebug(
                    "Scheduled job {JobName} ({JobId}) with cron {CronExpression}",
                    schedule.Schedule.Name,
                    schedule.Id,
                    schedule.Schedule.CronExpression);
            }

            return(Task.CompletedTask);
        }
        private string CreateCore(BackgroundTaskEnvelope task, Func <string, IState> createState)
        {
            var queue = this.GetQueueForTask(task);

            if (this._logger.IsEnabled(LogLevel.Debug))
            {
                this._logger.LogDebug("Enqueuing task. task_type={0} queue={1}", task.GetType().Name, queue);
            }

            var id = this._jobClient.Create(
                Job.FromExpression <HangfireTaskExecutor>(e => e.Execute(
                                                              new HangfireBackgroundTaskWrapper(task),
                                                              null,
                                                              CancellationToken.None)),
                createState(queue));

            return(id);
        }
Ejemplo n.º 5
0
        private string CreateCore(BackgroundTaskEnvelope task, Func <string, IState> createState)
        {
            var queue = GetQueueForTask(task.Task);

            if (this._logger.IsEnabled(LogLevel.Debug))
            {
                this._logger.LogDebug("Enqueuing task {TaskType} to {Queue}", task.GetType().Name, queue);
            }

            var hangfireBackgroundTaskEnvelope = new HangfireBackgroundTaskWrapper(task);

            task.Headers = new Dictionary <string, string>();

            using var activity = TaskExecutor.ActivitySource.StartActivity($"{hangfireBackgroundTaskEnvelope.Envelope.Task.GetType()} send", ActivityKind.Producer);

            ActivityContext contextToInject = default;

            if (activity != null)
            {
                contextToInject = activity.Context;
            }
            else if (Activity.Current != null)
            {
                contextToInject = Activity.Current.Context;
            }

            TaskExecutor.Propagator.Inject(
                new PropagationContext(contextToInject, Baggage.Current),
                task.Headers,
                (c, k, v) => c[k] = v);

            activity?.SetTag("messaging.system", "hangfire");
            activity?.SetTag("messaging.destination", queue);
            activity?.SetTag("messaging.destination_kind", "queue");

            var id = this._jobClient.Create(
                Job.FromExpression <HangfireTaskExecutor>(e => e.Execute(
                                                              hangfireBackgroundTaskEnvelope,
                                                              null,
                                                              CancellationToken.None)),
                createState(queue));

            return(id);
        }
 /// <inheritdoc />
 public Task <string> ScheduleAsync(BackgroundTaskEnvelope task, TimeSpan delay)
 {
     return(Task.FromResult(this.CreateCore(task, _ => new ScheduledState(delay))));
 }
 /// <inheritdoc />
 public Task <string> EnqueueAsync(BackgroundTaskEnvelope task)
 {
     return(Task.FromResult(this.CreateCore(task, queue => new EnqueuedState(queue))));
 }