Esempio n. 1
0
 /// <summary>
 /// 添加任务列表
 /// </summary>
 /// <param name="tasks"></param>
 /// <param name="weight"></param>
 /// <returns>开始任务数量</returns>
 public int AddTasks(IList <IAsyncTask> tasks, float weight = 1)
 {
     lock (mLock)
     {
         if (IsDone || weight <= 0 || tasks == null || tasks.Count == 0)
         {
             return(0);
         }
         float eweight = weight / tasks.Count;
         int   len     = 0;
         for (int i = 0; i < tasks.Count; i++)
         {
             IAsyncTask task = tasks[i];
             if (task != null && !task.IsDone)
             {
                 Task t = new Task();
                 t.task        = task;
                 t.weight      = eweight;
                 mTotalWeight += eweight;
                 mTasks.Add(t);
                 if (mStarted)
                 {
                     task.Start();
                 }
                 len++;
             }
         }
         return(len);
     }
 }
Esempio n. 2
0
 /// <inheritdoc />
 public void Initialize()
 {
     if (_inputQueueName == null)
     {
         return;
     }
     _expiredMessagesCleanupTask.Start();
 }
Esempio n. 3
0
        public void Initialize()
        {
            _configuredNumberOfWorkers = _options.NumberOfWorkers;

            _log.Info("Initializing circuit breaker with default number of workers = {count}", _configuredNumberOfWorkers);

            _resetCircuitBreakerTask.Start();
        }
        /// <summary>
        /// Initializes the transport by starting a task that deletes expired messages from the SQL table
        /// </summary>
        public void Initialize()
        {
            if (_receiveTableName == null)
            {
                return;
            }

            _expiredMessagesCleanupTask.Start();
        }
        /// <summary>
        /// Initializes the instance
        /// </summary>
        public void Initialize()
        {
            if (_lockTableName == null)
            {
                return;
            }

            _expiredLocksCleanupTask.Start();
        }
Esempio n. 6
0
        /// <summary>
        /// Initializes the in-mem error tracker - starts a background task that periodically cleans up tracked errors that haven't had any activity for 10 minutes or more
        /// </summary>
        public void Initialize()
        {
            // if it's a one-way client, then there's no reason to start the task
            if (string.IsNullOrWhiteSpace(_transport.Address))
            {
                return;
            }

            _cleanupOldTrackedErrorsTask.Start();
        }
Esempio n. 7
0
        /// <summary>
        /// Initialized the step (starts the <see cref="DueMessagesSenderTaskName"/> background task if using the internal timeout manager)
        /// </summary>
        public void Initialize()
        {
            // if the step has already been disposed, it is because it has been removed from the pipeline.... we might as well avoid doing stuff here, so let's just ignore the call
            if (_disposed)
            {
                return;
            }

            if (UsingExternalTimeoutManager)
            {
                _log.Info("Using external timeout manager with this address: '{0}'", _options.ExternalTimeoutManagerAddressOrNull);
            }
            else
            {
                _dueMessagesSenderBackgroundTask.Start();
            }
        }
        /// <summary>
        /// Initializes the transport by ensuring that the input queue has been created
        /// </summary>
        /// <inheritdoc />
        public void Initialize()
        {
            _disposables.Push(_messageLockRenewalTask);

            if (Address != null)
            {
                _log.Info("Initializing Azure Service Bus transport with queue {queueName}", Address);

                InnerCreateQueue(Address);

                CheckInputQueueConfiguration(Address);

                _messageReceiver = _tokenProvider == null
                    ?
                                   new MessageReceiver(
                    _connectionString,
                    Address,
                    receiveMode: ReceiveMode.PeekLock,
                    retryPolicy: DefaultRetryStrategy,
                    prefetchCount: _prefetchCount
                    )
                    :
                                   new MessageReceiver(
                    _endpoint,
                    Address,
                    _tokenProvider,
                    transportType: _transportType,
                    receiveMode: ReceiveMode.PeekLock,
                    retryPolicy: DefaultRetryStrategy,
                    prefetchCount: _prefetchCount
                    );

                _disposables.Push(_messageReceiver.AsDisposable(m => AsyncHelpers.RunSync(async() => await m.CloseAsync().ConfigureAwait(false))));

                if (AutomaticallyRenewPeekLock)
                {
                    _messageLockRenewalTask.Start();
                }

                return;
            }

            _log.Info("Initializing one-way Azure Service Bus transport");
        }
Esempio n. 9
0
 /// <summary>
 /// 添加任务
 /// </summary>
 /// <param name="task"></param>
 /// <param name="weight"></param>
 /// <returns></returns>
 public bool AddTask(IAsyncTask task, float weight = 1)
 {
     lock (mLock)
     {
         if (IsDone || task == null || task.IsDone || weight <= 0)
         {
             return(false);
         }
         Task t = new Task();
         t.task        = task;
         t.weight      = weight;
         mTotalWeight += weight;
         mTasks.Add(t);
         if (mStarted)
         {
             task.Start();
         }
         return(true);
     }
 }
        /// <summary>
        /// Initialized the step (starts the <see cref="DueMessagesSenderTaskName"/> background task if using the internal timeout manager)
        /// </summary>
        public void Initialize()
        {
            // if the step has already been disposed, it is because it has been removed from the pipeline.... we might as well avoid doing stuff here, so let's just ignore the call
            if (_disposed)
            {
                return;
            }

            if (UsingExternalTimeoutManager)
            {
                _log.Info("Using external timeout manager with this address: {queueName}", _options.ExternalTimeoutManagerAddressOrNull);
                return;
            }

            // ATM this is the best way to detect that the timeout manager is disabled and we therefore should not start the background task that polls for due messages
            if (_timeoutManager is DisabledTimeoutManager)
            {
                return;
            }

            _dueMessagesSenderBackgroundTask.Start();
        }
Esempio n. 11
0
        /// <summary>
        /// Receives the next message from the input queue. Returns null if no message was available
        /// </summary>
        public async Task <TransportMessage> Receive(ITransactionContext context, CancellationToken cancellationToken)
        {
            var receivedMessage = await ReceiveInternal().ConfigureAwait(false);

            if (receivedMessage == null)
            {
                return(null);
            }

            var message         = receivedMessage.Message;
            var messageReceiver = receivedMessage.MessageReceiver;

            if (!message.SystemProperties.IsLockTokenSet)
            {
                throw new RebusApplicationException($"OMG that's weird - message with ID {message.MessageId} does not have a lock token!");
            }

            var lockToken = message.SystemProperties.LockToken;
            var messageId = message.MessageId;

            CancellationTokenSource cancellationTokenSource = null;
            IAsyncTask renewalTask = null;

            if (AutomaticallyRenewPeekLock && !_prefetchingEnabled)
            {
                var now                 = DateTime.UtcNow;
                var leaseDuration       = message.SystemProperties.LockedUntilUtc - now;
                var lockRenewalInterval = TimeSpan.FromMinutes(0.5 * leaseDuration.TotalMinutes);

                cancellationTokenSource = new CancellationTokenSource();
                renewalTask             = _asyncTaskFactory
                                          .Create(description: $"RenewPeekLock-{messageId}",
                                                  action: () => RenewPeekLock(messageReceiver, messageId, lockToken, cancellationTokenSource),
                                                  intervalSeconds: (int)lockRenewalInterval.TotalSeconds,
                                                  prettyInsignificant: true
                                                  );

                cancellationTokenSource.Token.Register(renewalTask.Dispose);

                renewalTask.Start();
            }

            context.OnCompleted(async ctx =>
            {
                try
                {
                    await messageReceiver.CompleteAsync(lockToken).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    throw new RebusApplicationException(exception,
                                                        $"Could not complete message with ID {message.MessageId} and lock token {lockToken}");
                }

                // Dispose the renewal task after the message has been removed.
                // Note that we could get a MessageLockLostException and log an error in RenewPeekLock in the off chance that renewal runs between CompleteAsync and Dispose here,
                // but that's better than disposing the renewal first and potentially loosing the lock before calling complete.
                renewalTask?.Dispose();
            });

            context.OnAborted(async ctx =>
            {
                // Dispose the renewal before abandoning the message, otherwise renewal could grab the lock again.
                renewalTask?.Dispose();

                try
                {
                    await messageReceiver.AbandonAsync(lockToken).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    throw new RebusApplicationException(exception,
                                                        $"Could not abandon message with ID {message.MessageId} and lock token {lockToken}");
                }
            });

            context.OnDisposed(ctx =>
            {
                renewalTask?.Dispose();
                cancellationTokenSource?.Dispose();
            });

            var userProperties = message.UserProperties;
            var headers        = userProperties.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());
            var body           = message.Body;

            return(new TransportMessage(headers, body));
        }
Esempio n. 12
0
 public void Initialize()
 {
     _logger.Info("Initializing auto-scaler - will add up to {0} workers", _maximumNumberOfWorkers);
     _task.Start();
 }
Esempio n. 13
0
 /// <inheritdoc />
 public void Initialize()
 {
     _expiredMessagesCleanupTask?.Start();
 }
Esempio n. 14
0
 /// <summary>
 /// Initializes the in-mem error tracker - starts a background task that periodically cleans up tracked errors that haven't had any activity for 10 minutes or more
 /// </summary>
 public void Initialize()
 {
     _cleanupOldTrackedErrorsTask.Start();
 }
Esempio n. 15
0
 public void Initialize()
 {
     _cleanupTask.Start();
 }