Esempio n. 1
0
        public async override Task Execute(IJobExecutionContext context)
        {
            var worker        = (IBackgroundWorker)ServiceProvider.GetService(typeof(TWorker));
            var workerContext = new PeriodicBackgroundWorkerContext(ServiceProvider);

            switch (worker)
            {
            case AsyncPeriodicBackgroundWorkerBase asyncWorker:
            {
                if (_doWorkAsyncMethod != null)
                {
                    await(Task) _doWorkAsyncMethod.Invoke(asyncWorker, new object[] { workerContext });
                }

                break;
            }

            case PeriodicBackgroundWorkerBase syncWorker:
            {
                if (_doWorkMethod != null)
                {
                    _doWorkMethod.Invoke(syncWorker, new object[] { workerContext });
                }

                break;
            }
            }
        }
Esempio n. 2
0
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            Logger.LogWarning("Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext");
            await _configLoader.LoadFromDbIfChangedAsync(_lastSyncTime);

            _lastSyncTime = DateTime.UtcNow;
        }
 protected async override Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     await workerContext
     .ServiceProvider
     .GetRequiredService <TokenCleanupService>()
     .CleanAsync();
 }
Esempio n. 4
0
 protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     await workerContext
     .ServiceProvider
     .GetRequiredService <TokenCleanupService>()
     .CleanAsync()
     .ConfigureAwait(false);
 }
Esempio n. 5
0
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            Logger.LogInformation("Iniciando: Actualizacion de cotizacion de colones");

            await Task.CompletedTask;

            Logger.LogInformation("Finalizado: Actualizacion de cotizacion de colones");
        }
        /// <summary>
        /// 执行定期任务.
        /// </summary>
        /// <param name="workerContext"></param>
        protected override void DoWork(PeriodicBackgroundWorkerContext workerContext)
        {
            // 最好使用 PeriodicBackgroundWorkerContext 解析依赖 而不是构造函数.
            // 因为 AsyncPeriodicBackgroundWorkerBase 使用 IServiceScope 在你的任务执行结束时会对其 disposed.
            // 使用属性注入也可以
            var schoolRepository = workerContext.ServiceProvider.GetService <IProductRepository>();

            _count++;
        }
Esempio n. 7
0
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            using (var scope = AuditingManager.BeginScope())
            {
                await base.DoWorkAsync(workerContext);

                await scope.SaveAsync();
            }
        }
Esempio n. 8
0
        protected async override Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            var store = workerContext.ServiceProvider.GetRequiredService <IBackgroundJobStore>();

            var waitingJobs = await store.GetWaitingJobsAsync(WorkerOptions.MaxJobFetchCount);

            if (!waitingJobs.Any())
            {
                return;
            }

            var jobExecuter = workerContext.ServiceProvider.GetRequiredService <IBackgroundJobExecuter>();
            var clock       = workerContext.ServiceProvider.GetRequiredService <IClock>();
            var serializer  = workerContext.ServiceProvider.GetRequiredService <IBackgroundJobSerializer>();

            foreach (var jobInfo in waitingJobs)
            {
                jobInfo.TryCount++;
                jobInfo.LastTryTime = clock.Now;

                try
                {
                    var jobConfiguration = JobOptions.GetJob(jobInfo.JobName);
                    var jobArgs          = serializer.Deserialize(jobInfo.JobArgs, jobConfiguration.ArgsType);
                    var context          = new JobExecutionContext(workerContext.ServiceProvider, jobConfiguration.JobType, jobArgs);

                    try
                    {
                        await jobExecuter.ExecuteAsync(context);

                        await store.DeleteAsync(jobInfo.Id);
                    }
                    catch (BackgroundJobExecutionException)
                    {
                        var nextTryTime = CalculateNextTryTime(jobInfo, clock);

                        if (nextTryTime.HasValue)
                        {
                            jobInfo.NextTryTime = nextTryTime.Value;
                        }
                        else
                        {
                            jobInfo.IsAbandoned = true;
                        }

                        await TryUpdateAsync(store, jobInfo);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                    jobInfo.IsAbandoned = true;
                    await TryUpdateAsync(store, jobInfo);
                }
            }
        }
Esempio n. 9
0
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            var hostRunningToken = workerContext.ServiceProvider
                                   .GetRequiredService <HostRunningToken>();
            var licenseClient = workerContext.ServiceProvider
                                .GetRequiredService <LicenseClient>();
            var isOnline = await licenseClient.IsOnline();

            if (!isOnline)
            {
                hostRunningToken.Cancel();
            }
        }
Esempio n. 10
0
        protected async override Task DoWorkAsync(
            PeriodicBackgroundWorkerContext workerContext)
        {
            Logger.LogInformation("Starting: Setting status of inactive FileChecker...");

            var _repository = workerContext
                              .ServiceProvider
                              .GetRequiredService <IFileRepository>();

            var compareTime = DateTime.Now.AddDays(-7);
            var query       = (await _repository.GetQueryableAsync()).Where(x => x.FileContainerName == FileContainerNameConsts.Temp && x.CreationTime < compareTime);

            Logger.LogInformation("Completed: Setting status of inactive FileChecker...");
        }
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            // 获取货币汇率并执行更新
            var exchangeRate = await _exchangeRateApiService.QueryAsync();

            var currencies = await _reository.GetAllListAsync();

            foreach (var currency in currencies)
            {
                if (exchangeRate.ContainsKey(currency.CurrencyCode))
                {
                    currency.UpdateExchangeRate(exchangeRate[currency.CurrencyCode]);
                }
            }
        }
        /// <summary>
        /// 异步执行任务
        /// </summary>
        /// <param name="workerContext"></param>
        /// <returns></returns>
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            var tables = new[]
            {
                Initializer.GetPublishedTableName(),
                Initializer.GetReceivedTableName()
            };

            foreach (var table in tables)
            {
                Logger.LogDebug($"Collecting expired data from table: {table}");
                var time = DateTime.Now;
                await Storage.DeleteExpiresAsync(table, time, Options.CleanUpExpiresMessageBatch);
            }
        }
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            try
            {
                var store = workerContext.ServiceProvider.GetRequiredService <INotificationStore>();
                Logger.LogDebug("Before cleanup exprition jobs...");
                await store.DeleteNotificationAsync(Options.CleanupBatchSize);

                Logger.LogDebug("Exprition jobs cleanup job was successful...");
            }
            catch (Exception ex)
            {
                Logger.LogWarning("Exprition jobs cleanup job was failed...");
                Logger.LogWarning("Error:{0}", ex.Message);
            }
        }
    public override async Task DoWorkAsync()
    {
        var workerContext = new PeriodicBackgroundWorkerContext(ServiceProvider);
        var worker        = ServiceProvider.GetRequiredService <TWorker>();

        switch (worker)
        {
        case AsyncPeriodicBackgroundWorkerBase asyncPeriodicBackgroundWorker:
            await(Task) _doWorkAsyncMethod.Invoke(asyncPeriodicBackgroundWorker, new object[] { workerContext });
            break;

        case PeriodicBackgroundWorkerBase periodicBackgroundWorker:
            _doWorkMethod.Invoke(periodicBackgroundWorker, new object[] { workerContext });
            break;
        }
    }
Esempio n. 15
0
    protected async override Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
    {
        await using (var handle = await DistributedLock.TryAcquireAsync(nameof(TokenCleanupBackgroundWorker)))
        {
            Logger.LogInformation($"Lock is acquired for {nameof(TokenCleanupBackgroundWorker)}");

            if (handle != null)
            {
                await workerContext
                .ServiceProvider
                .GetRequiredService <TokenCleanupService>()
                .CleanAsync();

                Logger.LogInformation($"Lock is released for {nameof(TokenCleanupBackgroundWorker)}");
                return;
            }

            Logger.LogInformation($"Handle is null because of the locking for : {nameof(TokenCleanupBackgroundWorker)}");
        }
    }
Esempio n. 16
0
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            Logger.LogDebug("Starting: {0}", GetType());

            IClock clock = workerContext.ServiceProvider.GetRequiredService <IClock>();

            if (clock.Now.Hour == 0 && clock.Now.Minute == 3)
            {
                Logger.LogInformation("Starting: {0}", GetType());
                IFileCrawlerRepository fileCrawlerRepository = workerContext.ServiceProvider.GetRequiredService <IFileCrawlerRepository>();
                List <FileCrawler>     fileCrawlerList       = await fileCrawlerRepository.GetListAsync();

                FileCrawlerRecordDomainService recordDomainService = workerContext.ServiceProvider.GetRequiredService <FileCrawlerRecordDomainService>();
                foreach (FileCrawler fileCrawler in fileCrawlerList)
                {
                    await recordDomainService.InsertAsync(fileCrawler, clock.Now.Date);
                }
                Logger.LogInformation("Completed: {0}", GetType());
            }

            Logger.LogDebug("Completed: {0}", GetType());
        }
 protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     await DoReconnectionJobAsync();
 }
 protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     await ProcessDownloadJobAsync();
 }
Esempio n. 19
0
 protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     Debug.WriteLine($"Doing some work here");
     await Task.Delay(5000);
 }
 protected abstract Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext);
Esempio n. 21
0
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            Logger.LogInformation("Starting at {0}: Monitoring the website’s health...", stopwatch.Elapsed.Milliseconds);

            var guidGenerator     = workerContext.ServiceProvider.GetRequiredService <IGuidGenerator>();
            var unitOfWorkManager = workerContext.ServiceProvider.GetRequiredService <UnitOfWorkManager>();
            var monitorRepository = workerContext.ServiceProvider.GetRequiredService <IMonitorRepository>();
            var clientFactory     = workerContext.ServiceProvider.GetRequiredService <IHttpClientFactory>();

            var monitors = await monitorRepository.GetListByStepFilterAsync(MonitorStepTypes.Request);

            monitors = monitors
                       .Where(x =>
                              x.LastModificationTime == null
                        ? x.CreationTime.ToUniversalTime().AddSeconds(x.MonitorStep.Interval) < DateTime.UtcNow
                        : x.LastModificationTime?.ToUniversalTime().AddMinutes(x.MonitorStep.Interval) <
                              DateTime.UtcNow)
                       .ToList();

            foreach (var monitor in monitors)
            {
                if (!monitor.MonitorStep.Url.IsNullOrEmpty())
                {
                    var logInterval    = monitor.MonitorStep.Interval;
                    var monitorStepLog = new MonitorStepLog(
                        guidGenerator.Create(),
                        monitor.Id,
                        DateTime.UtcNow,
                        MonitorStepStatusTypes.Processing,
                        logInterval);

                    monitor.AddMonitorStepLog(monitorStepLog);

                    monitorStepLog.Status = MonitorStepStatusTypes.Processing;

                    await monitorRepository.UpdateAsync(monitor);

                    await unitOfWorkManager.Current.SaveChangesAsync();

                    try
                    {
                        var client = clientFactory.CreateClient();
                        client.Timeout = TimeSpan.FromSeconds(15);
                        var response = await client.GetAsync(monitor.MonitorStep.Url);

                        monitorStepLog.Status = MonitorStepStatusTypes.Pending;
                        if (response.IsSuccessStatusCode)
                        {
                            monitorStepLog.Status = MonitorStepStatusTypes.Success;
                        }
                        else
                        {
                            monitorStepLog.Status = MonitorStepStatusTypes.Fail;
                        }
                    }
                    catch (HttpRequestException rex)
                    {
                        monitorStepLog.SetLog(rex.Message);
                        monitorStepLog.Status = MonitorStepStatusTypes.Fail;
                    }
                    catch (Exception ex)
                    {
                        monitorStepLog.SetLog(ex.Message);
                        monitorStepLog.Status = MonitorStepStatusTypes.Error;
                    }
                    finally
                    {
                        monitorStepLog.EndDate = DateTime.UtcNow;
                    }

                    switch (monitorStepLog.Status)
                    {
                    case MonitorStepStatusTypes.Success:
                        monitor.MonitorStep.Status = MonitorStepStatusTypes.Success;
                        monitor.MonitorStatus      = MonitorStatusTypes.Up;
                        break;

                    case MonitorStepStatusTypes.Error:
                        monitor.MonitorStep.Status = MonitorStepStatusTypes.Error;
                        monitor.MonitorStatus      = MonitorStatusTypes.Warning;
                        break;

                    default:
                        monitor.MonitorStep.Status = MonitorStepStatusTypes.Fail;
                        monitor.MonitorStatus      = MonitorStatusTypes.Down;
                        break;
                    }
                }

                monitor.LastModificationTime = DateTime.UtcNow;

                await monitorRepository.UpdateAsync(monitor);

                await unitOfWorkManager.Current.SaveChangesAsync();

                await PublishUserNotifyEvent(monitor);
            }

            stopwatch.Stop();
            var stopwatchElapsed = stopwatch.Elapsed;

            Logger.LogInformation("Completed at {0} ms: Monitoring the website’s health...", stopwatchElapsed.TotalMilliseconds);
        }
 protected override Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     _Count++;
     return(Task.CompletedTask);
 }
 protected override Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     Console.WriteLine("from async background worker 3");
     return(Task.CompletedTask);
 }
        /*
         * private async Task InitAsync(PeriodicBackgroundWorkerContext workerContext)
         * {
         *  var pipelineHistoryRepository = workerContext.ServiceProvider
         *      .GetRequiredService<IRepository<PipelineHistory, int>>();
         *
         *  _pipelineHistoryIdList = await pipelineHistoryRepository.Where(p => !p.()).Select(p => p.Id).ToListAsync();
         * }
         */

        private async Task <PipelineHistory> UpdatePipelineHistoryAsync(int pipelineHistoryId, PeriodicBackgroundWorkerContext workerContext)
        {
            var pipelineHistoryRepository = workerContext.ServiceProvider
                                            .GetRequiredService <IRepository <PipelineHistory, int> >();
            var pipelineHistoryService = workerContext.ServiceProvider
                                         .GetRequiredService <PipelineHistoryService>();

            var pipelineRunStatus = await pipelineHistoryService.GetStatusAsync(pipelineHistoryId.ToString());

            var pipelineHistory = await pipelineHistoryRepository.GetAsync(pipelineHistoryId);

            var nodeDic = Digram.CreateInstance(pipelineHistory.Diagram).NodeList.ToDictionary(t => t.Id);

            pipelineRunStatus.TaskRunStatusList.ForEach(t => {
                t.TaskAnnoName = nodeDic[t.ShapeId].AnnoName;
                t.ConfigUrl    = nodeDic[t.ShapeId].ConfigUrl;
                t.ResultUrl    = nodeDic[t.ShapeId].ResultUrl;
                nodeDic[t.ShapeId].Destination.ForEach(id => t.NextShapes.Add(id));

                if (t.Log == null)
                {
                    return;
                }
                if (t.Log.StartTime == null)
                {
                    t.Log.ExecTime = null;
                }
                else if (t.Log.CompletionTime == null)
                {
                    t.Log.ExecTime = DateTime.Now - t.Log.StartTime;
                }
                else
                {
                    t.Log.ExecTime = t.Log.CompletionTime - t.Log.StartTime;
                }
            });

            /*pipelineHistory
             *  .SetStatus(
             *      pipelineRunStatus.Status,
             *      pipelineRunStatus.StartTime,
             *      pipelineRunStatus.CompletionTime,
             *      pipelineRunStatus.Percent,
             *      pipelineRunStatus.Logs)*/
            pipelineHistory
            .SetStatus(pipelineRunStatus.Status)
            .SetStartTime(pipelineRunStatus.StartTime)
            .SetCompletionTime(pipelineRunStatus.CompletionTime)
            .SetPercent(pipelineRunStatus.Percent)
            .SetLogs(pipelineRunStatus.Logs)
            .SetMessage(pipelineRunStatus.Message);

            await pipelineHistoryRepository.UpdateAsync(pipelineHistory);

            return(pipelineHistory);
        }
Esempio n. 25
0
 protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     //retrieve data from api and save to database
     await _theMovieDbApiIntegrationService.RetrieveTopRatedMovieResult();
 }
        protected override async Task DoWorkAsync(
            PeriodicBackgroundWorkerContext workerContext)
        {
            /*
             * if (!_isInited)
             * {
             *  await InitAsync(workerContext);
             *  _isInited = true;
             * }
             */

            int pipelineHistoryId = 0;

            while (PipelineHistoryCreatedQueue.TryDequeue(out pipelineHistoryId))
            {
                _pipelineHistoryTobeCheckSet.Add(pipelineHistoryId);
            }

            var pipelineHistoryService = workerContext.ServiceProvider
                                         .GetRequiredService <PipelineHistoryService>();
            var pipelineHistoryTobeUncheckSet = new HashSet <int>();

            foreach (var pipelineHistoryTobeCheck in  _pipelineHistoryTobeCheckSet)
            {
                try{
                    var pipelineHistory = await UpdatePipelineHistoryAsync(pipelineHistoryTobeCheck, workerContext);

                    if (pipelineHistory.IsFinish())
                    {
                        pipelineHistoryService.DeletePipelinerun(pipelineHistory.Id);
                        pipelineHistoryTobeUncheckSet.Add(pipelineHistoryTobeCheck);
                    }
                }
                catch (Exception e) {
                    Console.WriteLine(e);
                }
            }
            _pipelineHistoryTobeCheckSet.RemoveWhere(p => pipelineHistoryTobeUncheckSet.Contains(p));

            while (PipelineHistoryTobeDeleteQueue.TryDequeue(out pipelineHistoryId))
            {
                if (_pipelineHistoryTobeCheckSet.Contains(pipelineHistoryId))
                {
                    pipelineHistoryService.DeletePipelinerun(pipelineHistoryId);
                    _pipelineHistoryTobeCheckSet.Remove(pipelineHistoryId);
                }
                pipelineHistoryService.DeletePVC(pipelineHistoryId);
            }


            /*
             * for (int i = _pipelineHistoryIdList.Count - 1; i >= 0; i--)
             * {
             *  try{
             *      var pipelineHistory = await UpdatePipelineHistoryAsync(_pipelineHistoryIdList[i], workerContext);
             *      if (pipelineHistory.IsFinish()) _pipelineHistoryIdList.RemoveAt(i);
             *  }
             *  catch (Exception e) {
             *      Console.WriteLine(e);
             *  }
             * }
             */
        }
 protected override void DoWork(PeriodicBackgroundWorkerContext workerContext)
 {
     Console.WriteLine("periodic worker 2 is started");
 }
 protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
 {
     await ProcessPeerDiscoveryJobAsync();
 }
Esempio n. 29
0
 /// <summary>
 /// Periodic works should be done by implementing this method.
 /// </summary>
 protected abstract void DoWork(PeriodicBackgroundWorkerContext workerContext);