Exemple #1
0
 /// <summary>
 /// Сброс задачи. После чего она будет готова к выполнению через заданный период.
 /// </summary>
 public void Reset()
 {
     ConditionalLock(() =>
     {
         Interlocked.Exchange(ref _executionsCount, 0);
         _startedTimeMSec = TimerJob.GetNowMSec();
     });
 }
Exemple #2
0
 /// <summary>
 /// Активация задачи. После чего она сразу готова к выполнению.
 /// </summary>
 public void Activate()
 {
     ConditionalLock(() =>
     {
         Interlocked.Exchange(ref _executionsCount, 0);
         _startedTimeMSec = TimerJob.GetNowMSec() - _periodMSec;
     });
 }
Exemple #3
0
        /// <summary>
        /// Возвращает время от текущего момента до следующего исполнения.
        /// </summary>
        /// <returns></returns>
        public long GetMSecToNextExecution()
        {
            long nextTime = 0;

            ConditionalLock(() =>
            {
                nextTime = _startedTimeMSec + (Interlocked.Read(ref _executionsCount) + 1) * _periodMSec;
            });

            return(nextTime - TimerJob.GetNowMSec());
        }
        private void ExecuteJobsInfinitely(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                // Получение времени ожидания до ближайшей задачи.
                TimerJob job   = GetNearestJob();
                var      delay = (job == null) ? JOB_LIST_CHECK_PERIOD : job.GetMSecToNextExecution();

                if (delay > 0)
                {
                    Thread.Sleep((int)delay);
                    continue;
                }

                ExecuteOrThrow(job);
            }
        }
        private void ExecuteOrThrow(TimerJob job)
        {
            try
            {
                job.Execute();
            }
            catch (Exception ex)
            {
                var text = $"TimerJobScheduler. Exception in job: " +
                           $"{job.CallingAssemblyName}\n{ex.Message}\n{ex.StackTrace}";
                _logger?.LogCritical(ex, text);

                if (_throwJobException)
                {
                    throw;
                }
            }
        }
        private TimerJob GetNearestJob()
        {
            if (_timerJobs.IsEmpty)
            {
                return(null);
            }

            TimerJob nearestJob = null;
            long     minTime    = long.MaxValue;

            foreach (var timerJob in _timerJobs)
            {
                long time = timerJob.GetMSecToNextExecution();
                if (time < minTime)
                {
                    nearestJob = timerJob;
                    minTime    = time;
                }
            }

            return(nearestJob);
        }
 /// <summary>
 /// Добавление задачи.
 /// </summary>
 public void AddJob(TimerJob job)
 {
     _timerJobs.Add(job);
 }