Example #1
0
        /// <summary>
        /// แจ้งเตือนนัดหมาย
        /// </summary>
        /// <param name="appointmentModel">ข้อมูลงาน</param>
        /// <returns></returns>
        public async Task <AppointmentModel> AddAppointmentAsync(AppointmentModel appointmentModel)
        {
            string jobsId = "";

            switch (appointmentModel.JobsType)
            {
            case JobsTypeUtility.FIRE_AND_FORGET:
                jobsId = _backgroundJobClient.Enqueue(
                    () => Console.WriteLine($"id {appointmentModel.AppointmentId} key {appointmentModel.AppointmentKey}")
                    );
                break;

            case JobsTypeUtility.DELAYED:
                DateTime now = DateTime.UtcNow;
                if (appointmentModel.TriggerDate.Value.Kind != DateTimeKind.Utc)
                {
                    appointmentModel.TriggerDate = appointmentModel.TriggerDate.Value.ToUniversalTime();
                }
                TimeSpan difference = appointmentModel.TriggerDate.Value.Subtract(now);
                jobsId = _backgroundJobClient.Schedule(
                    () => Console.WriteLine($"id {appointmentModel.AppointmentId} key {appointmentModel.AppointmentKey}"),
                    difference
                    );
                break;
            }
            appointmentModel.JobsId = jobsId;
            return(appointmentModel);
        }
Example #2
0
        void Notify(InvoiceEntity invoice, int?eventCode = null, string name = null)
        {
            CancellationTokenSource cts = new CancellationTokenSource(10000);

            if (!String.IsNullOrEmpty(invoice.NotificationEmail))
            {
                // just extracting most important data for email body, merchant should query API back for full invoice based on Invoice.Id
                var ipn = new
                {
                    invoice.Id,
                    invoice.Status,
                    invoice.StoreId
                };
                // TODO: Consider adding info on ItemDesc and payment info (amount)

                var emailBody = NBitcoin.JsonConverters.Serializer.ToString(ipn);
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                _EmailSender.SendEmailAsync(invoice.NotificationEmail, $"BtcPayServer Invoice Notification - ${invoice.StoreId}", emailBody);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            if (string.IsNullOrEmpty(invoice.NotificationURL))
            {
                return;
            }
            var invoiceStr = NBitcoin.JsonConverters.Serializer.ToString(new ScheduledJob()
            {
                TryCount = 0, Invoice = invoice, EventCode = eventCode, Message = name
            });
            if (!string.IsNullOrEmpty(invoice.NotificationURL))
            {
                _JobClient.Schedule(() => NotifyHttp(invoiceStr), TimeSpan.Zero);
            }
        }
Example #3
0
        public void CountParrot(string userId, string channelId, DateTime currentTime)
        {
            if (!Utils.IsInTimespan(currentTime, TimeSpan.FromHours(MorningBreak), Tolerance) &&
                !Utils.IsInTimespan(currentTime, TimeSpan.FromHours(AfternoonBreak), Tolerance))
            {
                return;
            }

            _coffeeRepository.ConfirmUserReady(userId);

            if (_coffeeRepository.GetMissingParticipants().Count == 0)
            {
                LaunchCoffeeBreak(channelId);
                return;
            }

            var remindJob = _channelRepository.GetRemindJob();

            if (!string.IsNullOrEmpty(remindJob))
            {
                _backgroundJobClient.Delete(remindJob);
            }

            var newRemindJob = _backgroundJobClient.Schedule(() => CoffeeRemind(channelId), TimeSpan.FromSeconds(CoffeeRemindDelaySeconds));

            _channelRepository.SetRemindJob(newRemindJob);
        }
Example #4
0
        public override Task <RpcResult <TaskVoidRes> > ScheduleTransforAsync(ScheduleTaskReq req)
        {
            RpcResult <TaskVoidRes> res = new RpcResult <TaskVoidRes>();

            _jobClient.Schedule <IHangfireJobService>(x => x.Schedule(0, 1, req.Delay * 60, $"{req.ServiceId}|{req.MessageId}|{req.Data}", null), TimeSpan.FromMinutes(req.Delay));
            return(Task.FromResult(res));
        }
        /// <summary>
        ///   There may be old DB records that are not cleared out. This looks for them and queues a job to remove them
        /// </summary>
        /// <param name="cancellationToken"></param>
        private async Task DetectOldNonFinishedRecords(CancellationToken cancellationToken)
        {
            var cutoff = DateTime.UtcNow - AppInfo.OldMultipartUploadThreshold;

            var items = await database.InProgressMultipartUploads.Where(i => i.UpdatedAt < cutoff && !i.Finished)
                        .ToListAsync(cancellationToken);

            if (items.Count < 1)
            {
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            foreach (var item in items)
            {
                logger.LogError(
                    "Found old multipart upload data ({Id}) that has not finished or canceled, queueing a job to abort it",
                    item.Id);

                jobClient.Schedule <DeleteNonFinishedMultipartUploadJob>(
                    x => x.Execute(item.UploadId, CancellationToken.None),
                    AppInfo.MultipartUploadTotalAllowedTime + TimeSpan.FromHours(2));
            }
        }
Example #6
0
 public Task <IJobId> ScheduleAsync(IJob job, DateTimeOffset runAt, CancellationToken cancellationToken)
 {
     return(ScheduleAsync(
                job,
                cancellationToken,
                (c, d, n, j) => _backgroundJobClient.Schedule <IHangfireJobRunner>(r => r.ExecuteAsync(n, d.Name, d.Version, j), runAt)));
 }
        public override Task <RpcResult <VoidRes> > ScheduleAsync(ScheduleReq req)
        {
            RpcResult <VoidRes> res = new RpcResult <VoidRes>();

            _jobClient.Schedule <IJobService>(x => x.Schedule(req.ServiceId, req.MessageId, req.Data, null), TimeSpan.FromMinutes(req.Delay));
            return(Task.FromResult(res));
        }
Example #8
0
        public void Schedule(ICommand command, TimeSpan delay, string jobname = null)
        {
            var name = jobname ?? command.GetType().Name;

            _logger.LogInformation("Scheduling command {event}", name);
            name += GetJobRequestUserName(command.RequestUser);
            _backgroundJobClient.Schedule <SheaftDispatcher>(bridge => bridge.Execute(name, command, CancellationToken.None), delay);
        }
        public void ScheduleEnqueueAt([FromQuery] int randomInt)
        {
            var input = new ScheduledJobInput {
                Number = randomInt, ScheduleAt = DateTimeOffset.UtcNow
            };
            var enqueueAt = input.ScheduleAt.AddSeconds(5);

            _backgroundJobs.Schedule <IScheduledJob>(job => job.DoWork(input), enqueueAt);
        }
Example #10
0
        public string EnqueueDelay()
        {
            var id = _jobClient.Schedule(
                () => Console.WriteLine("Job de enfileiramento com delay de 10s executado"),
                TimeSpan.FromSeconds(10));

            _logger.LogInformation($"Job com delay de 10s enfileirado com ID: {id}");
            return(id);
        }
        async Task Notify(InvoiceEntity invoice, int?eventCode = null, string name = null)
        {
            CancellationTokenSource cts = new CancellationTokenSource(10000);

            if (!String.IsNullOrEmpty(invoice.NotificationEmail))
            {
                // just extracting most important data for email body, merchant should query API back for full invoice based on Invoice.Id
                var ipn = new
                {
                    invoice.Id,
                    invoice.Status,
                    invoice.StoreId
                };
                // TODO: Consider adding info on ItemDesc and payment info (amount)

                var emailBody = NBitcoin.JsonConverters.Serializer.ToString(ipn);
                await _EmailSender.SendEmailAsync(
                    invoice.NotificationEmail, $"BtcPayServer Invoice Notification - ${invoice.StoreId}", emailBody);
            }

            try
            {
                if (string.IsNullOrEmpty(invoice.NotificationURL))
                {
                    return;
                }
                _EventAggregator.Publish <InvoiceIPNEvent>(new InvoiceIPNEvent(invoice.Id, eventCode, name));
                var response = await SendNotification(invoice, eventCode, name, cts.Token);

                response.EnsureSuccessStatusCode();
                return;
            }
            catch (OperationCanceledException) when(cts.IsCancellationRequested)
            {
                _EventAggregator.Publish <InvoiceIPNEvent>(new InvoiceIPNEvent(invoice.Id, eventCode, name)
                {
                    Error = "Timeout"
                });
            }
            catch (Exception ex) // It fails, it is OK because we try with hangfire after
            {
                _EventAggregator.Publish <InvoiceIPNEvent>(new InvoiceIPNEvent(invoice.Id, eventCode, name)
                {
                    Error = ex.Message
                });
            }
            var invoiceStr = NBitcoin.JsonConverters.Serializer.ToString(new ScheduledJob()
            {
                TryCount = 0, Invoice = invoice, EventCode = eventCode, Message = name
            });

            if (!string.IsNullOrEmpty(invoice.NotificationURL))
            {
                _JobClient.Schedule(() => NotifyHttp(invoiceStr), TimeSpan.Zero);
            }
        }
Example #12
0
        public async Task <IHttpActionResult> Average(AverageProjectsModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            if (!AllProjectsExist(model.Projects))
            {
                return(NotFound());
            }

            var now     = DateTime.UtcNow;
            var project = new Project
            {
                UserId            = User.Identity.GetUserId(),
                TraceId           = Guid.NewGuid(),
                Name              = model.Name,
                FileName          = FormatStitchedFrom(model.Projects),
                TestName          = model.TestName,
                TestType          = model.TestType,
                Channel           = model.Channel,
                Tag               = model.Tag,
                Mass              = model.Mass,
                Area              = model.Area,
                Comments          = $"{model.Comments} {FormatStitchedFromNames(model.Projects)}",
                IsAveragePlot     = true,
                CreatedAt         = now,
                UpdatedAt         = now,
                StitchedFromNames = FormatStitchedFromNames(model.Projects),
            };

            _db.Projects.Add(project);
            await _db.SaveChangesAsync();

            var traceId = project.TraceId.ToString();

            project.JobId = _jobClient.Enqueue <IBackgroundProcessor>(
                p => p.PrepareAverageProject(
                    traceId,
                    project.Id,
                    model.Projects,
                    JobCancellationToken.Null));

            await _db.SaveChangesAsync();

            var timeoutJobId = _jobClient.Schedule <IBackgroundProcessor>(
                p => p.HandleTimeout(traceId, project.Id),
                _options.ProjectPrepareTimeout);

            _jobClient.ContinueWith <IBackgroundProcessor>(project.JobId,
                                                           p => p.CancelTimeout(traceId, project.Id, timeoutJobId),
                                                           JobContinuationOptions.OnAnyFinishedState);

            return(Ok());
        }
Example #13
0
        public void Notify(InvoiceEntity invoice)
        {
            var invoiceStr = NBitcoin.JsonConverters.Serializer.ToString(new ScheduledJob()
            {
                TryCount = 0, Invoice = invoice
            });

            if (!string.IsNullOrEmpty(invoice.NotificationURL))
            {
                _JobClient.Schedule(() => NotifyHttp(invoiceStr), TimeSpan.Zero);
            }
        }
Example #14
0
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            var project = GetAllUserProjects().SingleOrDefault(p => p.Id == key);

            if (project == null)
            {
                return(NotFound());
            }
            var userId = HttpContext.Current.User.Identity.GetUserId();

            var traceId = project.TraceId.ToString();

            _db.SP_DeleteProject(userId, key);
            _db.SaveChanges();

            if (!string.IsNullOrWhiteSpace(project.JobId) && _jobClient.Delete(project.JobId))
            {
                _jobClient.ContinueWith <IBackgroundProcessor>(project.JobId, p => p.DeleteProjectData(traceId, project.Id), JobContinuationOptions.OnAnyFinishedState);
                if (project.InternalFileName != null)
                {
                    if (_options.RawFileRetentionPeriod > TimeSpan.Zero)
                    {
                        _jobClient.Schedule <IBackgroundProcessor>(p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName), _options.RawFileRetentionPeriod);
                    }
                    else
                    {
                        _jobClient.ContinueWith <IBackgroundProcessor>(project.JobId, p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName), JobContinuationOptions.OnAnyFinishedState);
                    }
                }
            }
            else
            {
                _jobClient.Enqueue <IBackgroundProcessor>(p => p.DeleteProjectData(traceId, project.Id));
                if (project.InternalFileName != null)
                {
                    if (_options.RawFileRetentionPeriod > TimeSpan.Zero)
                    {
                        _jobClient.Schedule <IBackgroundProcessor>(p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName), _options.RawFileRetentionPeriod);
                    }
                    else
                    {
                        _jobClient.Enqueue <IBackgroundProcessor>(p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName));
                    }
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
 public void Schedule(PalestraId palestraId, DateTimeOffset dataExecucao)
 {
     _job.Schedule <ISendEmailLembreteOrganizador>(
         x => x.SendEmailLembrete(palestraId.Value),
         dataExecucao
         );
 }
Example #16
0
 public void SendEmail(string email, string subject, string message)
 {
     _JobClient.Schedule(async(cancellationToken) =>
     {
         var emailSettings = await GetEmailSettings();
         if (emailSettings?.IsComplete() != true)
         {
             Logs.Configuration.LogWarning("Should have sent email, but email settings are not configured");
             return;
         }
         using (var smtp = emailSettings.CreateSmtpClient())
         {
             var mail        = emailSettings.CreateMailMessage(new MailAddress(email), subject, message);
             mail.IsBodyHtml = true;
             try
             {
                 await smtp.SendMailAsync(mail).WithCancellation(cancellationToken);
             }
             catch (OperationCanceledException) when(cancellationToken.IsCancellationRequested)
             {
                 smtp.SendAsyncCancel();
             }
         }
     }, TimeSpan.Zero);
 }
Example #17
0
        private DougResponse SendChallenge(Command command)
        {
            var amount   = int.Parse(command.GetArgumentAt(1));
            var targetId = command.GetTargetUserId();
            var caller   = _userRepository.GetUser(command.UserId);
            var target   = _userRepository.GetUser(targetId);

            if (amount <= 0 || command.UserId == targetId)
            {
                return(new DougResponse(DougMessages.YouIdiot));
            }

            var challenge = _channelRepository.GetGambleChallenge(targetId);

            if (challenge != null)
            {
                return(new DougResponse(DougMessages.AlreadyChallenged));
            }

            _channelRepository.SendGambleChallenge(new GambleChallenge(command.UserId, targetId, amount));

            _backgroundJobClient.Schedule(() => ChallengeTimeout(targetId), TimeSpan.FromMinutes(3));

            _slack.BroadcastMessage(string.Format(DougMessages.ChallengeSent, _userService.Mention(caller), _userService.Mention(target), amount), command.ChannelId);
            _slack.SendEphemeralMessage(DougMessages.GambleChallengeTip, targetId, command.ChannelId);

            return(NoResponse);
        }
Example #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseHangfireDashboard();
            app.UseHangfireServer();
            //backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
            //backgroundJobs.Schedule(() => Console.WriteLine("Hola Mundo en cuarentena"),TimeSpan.FromMinutes(2));

            //var client = new RestClient("https://api.covid19api.com/summary");
            //client.Timeout = -1;
            //var request = new RestRequest(Method.GET);
            //IRestResponse response = client.Execute(request);

            Global global = new Global(12, 3, 2, 33, 2, 3);

            //backgroundJobs.Schedule(() => Console.WriteLine(global), TimeSpan.FromMinutes(1));
            backgroundJobs.Schedule(() => callRestClient("Hello"), TimeSpan.FromMinutes(1));
            //backgroundJobs.Schedule(() => Console.WriteLine(global), TimeSpan.FromMinutes(2));
            //backgroundJobs.Schedule(() => Console.WriteLine(global), TimeSpan.FromMinutes(3));

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        public ActionResult Delete(DeleteStackViewModel viewModel)
        {
            var stack = _stackRepository.FindAll().SingleOrDefault(x => x.Name == viewModel.StackModel.Name);

            if (stack == null)
            {
                // The user was looking at a stale list and the stack isn't even in the database anymore.
                // Redirect to the stack list and, from the user's perspective, the stack will have been deleted as requested.
                return(RedirectToAction("Index"));
            }

            var currentUserName             = _owinContext.Authentication.User.Identity.Name;
            var userHasPermissionForProfile = _userProfileAccessManager.UserHasPermissionForProfile(currentUserName, viewModel.SelectedProfileId);

            if (!userHasPermissionForProfile)
            {
                throw new InvalidOperationException("User does not have permission to use this profile.");
            }

            var profileId = viewModel.SelectedProfileId;
            var stackName = viewModel.StackModel.Name;

            _backgroundJobClient.Enqueue <DeleteStack>(x => x.Execute(viewModel.SelectedProfileId, stackName));

            // Wait 30 seconds before trying to update this stack so that there is time to for the CreateStack command to fire
            // and for AWS to do its thing. This is so we don't have to wait up to 5 minutes for the scheduled job to update the database
            // with the new stack info.
            _backgroundJobClient.Schedule <UpdateStack>(x => x.Execute(profileId, stackName), TimeSpan.FromSeconds(60));

            return(RedirectToAction("Index"));
        }
Example #20
0
        public async Task <Result <Nothing, Error> > Handle(RecordAcceptedTrainingInvitation.Command request, CancellationToken cancellationToken)
        {
            var user = await _userAccessor.GetUser();

            var enrollmentId        = EnrollmentId.With(request.EnrollmentId);
            var enrollmentReadModel = _enrollmentRepo.Query()
                                      .SingleOrDefault(x => x.Id == enrollmentId);

            if (enrollmentReadModel == null)
            {
                return(Result.Failure <Nothing, Error>(new Error.ResourceNotFound()));
            }

            var preferredTrainings = await _trainingRepository.GetByIds(enrollmentReadModel.PreferredTrainings.Select(x => x.ID).ToArray());

            var result = await _aggregateStore.Update <EnrollmentAggregate, EnrollmentId, Result <Nothing, Error> >(
                enrollmentId, CommandId.New,
                (aggregate) => aggregate.RecordCandidateAcceptedTrainingInvitation(request, user, preferredTrainings, _clock.GetCurrentInstant()),
                cancellationToken);

            if (result.Unwrap().IsSuccess)
            {
                var selectedTraining = preferredTrainings.Single(x => x.ID == request.SelectedTrainingID);
                _backgroundJobClient.Schedule(() => _engine.Execute(
                                                  new SendTrainingReminder.Command()
                {
                    EnrollmentId = request.EnrollmentId, TrainingId = request.SelectedTrainingID
                }),
                                              selectedTraining.StartDateTime.Minus(NodaTime.Duration.FromHours(24)).ToDateTimeOffset());
            }

            return(result.Unwrap());
        }
Example #21
0
        public async Task Execute(long id, CancellationToken cancellationToken)
        {
            var server = await Database.ExternalServers.FindAsync(id);

            if (CheckServerDataIsFineForProvisioning(id, server) || server == null)
            {
                return;
            }

            await PerformProvisioningCommands(server, GeneralProvisionCommandPart);

            server.StatusLastChecked = DateTime.UtcNow;
            server.BumpUpdatedAt();
            await Database.SaveChangesAsync(cancellationToken);

            // If not provisioned yet, need to requeue this job
            if (!server.ProvisionedFully)
            {
                Logger.LogTrace("External server {Id} not yet fully provisioned", id);
                jobClient.Schedule <ProvisionControlledServerJob>(x => Execute(id, CancellationToken.None),
                                                                  TimeSpan.FromSeconds(10));
            }
            else
            {
                Logger.LogTrace("External server {Id} is provisioned now", id);
            }
        }
        public void HangfireTest()
        {
            //Always dispose background server
            var hangfire = new BackgroundJobServer();

            hangfire.Dispose();

            _backgroundJobClient.Enqueue <HangfireService>(x => x.Test("Test Hangfire"));

            _backgroundJobClient.Enqueue <HangfireService>(h => h.Test("Test"));
            _backgroundJobClient.Enqueue(() => Console.WriteLine("Hello World for Hang-fire"));
            _backgroundJobClient.Schedule(() => Console.WriteLine("Schedule is started"), TimeSpan.FromMinutes(1));
            RecurringJob.AddOrUpdate("First RecurrringJob", () => Console.WriteLine("RecurringJob is running"), cronExpression: Cron.MinuteInterval(interval: 2));
            RecurringJob.RemoveIfExists("Test remove RecurringJob");
            RecurringJob.Trigger("First RecurringJob");
        }
        public void Execute(Guid stackId)
        {
            var stack = _stackRepository.Find(stackId);

            if (stack == null)
            {
                // nothing to do if the stack doesn't exist anymore
                return;
            }

            var primaryInstances = new List <string>();

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var id in stack.InstanceIds)
            {
                var instance = _instanceRepository.Find(id);
                if (instance != null)
                {
                    primaryInstances.Add(instance.ResourceId);
                }
            }

            // Only toggle the stack instances if the stack schedule is enabled
            // We do not end the chain of power on / power off cycles because
            // the enabled flag could be flipped between one run and the next
            if (stack.ScheduleEnabled)
            {
                _startInstances.Execute(stack.OwnerProfileId, primaryInstances);
            }

            var nextStopTimespan = _scheduleCalculator.GetNextStop(stack);

            _backgroundJobClient.Schedule <ScheduledStopStack>(x => x.Execute(stackId), nextStopTimespan);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAwwAppLogic logic, IAwwAppLinkDal dal, IBackgroundJobClient backgroundJobs)
        {
            dal.Clean();

            backgroundJobs.Schedule(() => logic.CacheLinks(10), TimeSpan.FromSeconds(30));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHangfireServer();

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                DashboardTitle = "Hangfire Jobs",
                Authorization  = new[]
                {
                    new  HangfireAuthorizationFilter("admin")
                }
            });

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        protected virtual async Task HandleEvent(DomainEvent domainEvent, CancellationToken cancellationToken)
        {
            var eventId  = domainEvent.GetType().FullName;
            var criteria = new WebhookSearchCriteria()
            {
                IsActive      = true,
                EventIds      = new[] { eventId },
                Skip          = 0,
                Take          = int.MaxValue,
                ResponseGroup = WebhookResponseGroup.Info.ToString()
            };

            var webHookSearchResult = await _webHookSearchService.SearchAsync(criteria);

            if (webHookSearchResult.TotalCount > 0)
            {
                var eventObject = domainEvent.GetEntityWithInterface <IEntity>()
                                  .Select(x => new { objectId = x.Id, objectType = x.GetType().FullName })
                                  .ToArray();

                var request = new WebhookRequest
                {
                    EventId     = eventId,
                    EventObject = JsonConvert.SerializeObject(eventObject),
                    WebHooks    = webHookSearchResult.Results
                };

                _backgroundJobClient.Schedule(() => NotifyAsync(request, cancellationToken), TimeSpan.FromMinutes(1));
            }
        }
        public async Task EvaluateAsync(MetricQuery query, CancellationToken cancellation = default)
        {
            var options = _optionsProvider.Value;

            var timeout  = query.Timeout.GetValueOrDefault(options.Metrics.Evaluation.Timeout);
            var interval = query.Interval.GetValueOrDefault(options.Metrics.Evaluation.Interval);

            try
            {
                _logger.LogInformation("Starting evaluation of query '{Query}'", query.Name);

                var result = await _queryExecutor.ExecuteAsync(query, timeout, cancellation);

                await _metricsWriter.WriteAsync(query, result, cancellation);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Query '{Query}' evaluation failed with exception", query.Name);
            }
            finally
            {
                _logger.LogInformation("Query '{Query}' evaluated. Next evaluation on '{NextOccurence}'", query.Name, (DateTime.Now + interval));

                // Re-schedule
                _jobClient.Schedule <ScheduledMetricsEvaluator>(
                    e => e.EvaluateAsync(query, cancellation), interval);
            }
        }
 public override string Schedule(IBackgroundJobClient jobClient)
 {
     return(jobClient.Schedule <StudentSupportEmailJobs>(
                jobs => jobs.SendVotingAlert(Entity.Id, JobCancellationToken.Null),
                GetIntendedRunAt()
                ));
 }
Example #28
0
        /// <inheritdoc />
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var options = _optionsProvider.Value;

            var allQueries = await _queriesProvider.GetAsync(stoppingToken);

            var schedulerQueries = allQueries.Where(q =>
            {
                if (q.EvaluationMode == MetricsEvaluationMode.Scheduled)
                {
                    return(true);
                }

                if (q.EvaluationMode == null && options.Metrics.Evaluation.Mode == MetricsEvaluationMode.Scheduled)
                {
                    return(true);
                }

                return(false);
            });

            foreach (var query in schedulerQueries)
            {
                var queryRef = query;

                _jobClient.Schedule <ScheduledMetricsEvaluator>(
                    e => e.EvaluateAsync(queryRef, stoppingToken), TimeSpan.Zero);

                _logger.LogInformation("Query '{Query}' successfully scheduled", query.Name);
            }

            _healthCheck.SchedulerInitialized = true;
        }
        public async Task Execute(long itemId, CancellationToken cancellationToken)
        {
            var item = await database.StorageItems.Include(i => i.StorageItemVersions)
                       .FirstOrDefaultAsync(i => i.Id == itemId, cancellationToken);

            if (item == null)
            {
                logger.LogError("Failed to get StorageItem ({ItemId}) for CI image locking", itemId);
                return;
            }

            if (item.WriteAccess == FileAccess.Nobody && item.Special)
            {
                logger.LogInformation("Skipping lock on StorageItem ({ItemId}) as it's already in nobody write mode",
                                      itemId);
                return;
            }

            // Queue jobs to delete other than the first uploaded version
            var lowestVersion = item.StorageItemVersions.Where(v => !v.Uploading).Min(v => v.Version);

            foreach (var version in item.StorageItemVersions)
            {
                if (version.Version == lowestVersion)
                {
                    if (version.Protected != true || version.Keep != true)
                    {
                        version.Protected = true;
                        version.Keep      = true;
                        version.BumpUpdatedAt();
                    }
                }
                else
                {
                    // This version needs to be deleted
                    jobClient.Schedule <DeleteStorageItemVersionJob>(x => x.Execute(version.Id, CancellationToken.None),
                                                                     TimeSpan.FromSeconds(30));
                }
            }

            item.WriteAccess = FileAccess.Nobody;
            item.Special     = true;
            item.BumpUpdatedAt();

            // Also mark all parent folders as special so that they can't be deleted
            foreach (var parent in await item.GetParentsRecursively(database))
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (parent.Special != true)
                {
                    parent.Special = true;
                    logger.LogInformation("CI image parent folder ({Id}) will be marked as special", parent.Id);
                }
            }

            await database.SaveChangesAsync(cancellationToken);

            logger.LogInformation("Use as CI image has locked writing to StorageItem ({ItemId})", itemId);
        }
Example #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient backgroundJobs)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHangfireDashboard(options: new DashboardOptions()
            {
                DashboardTitle = "hangfireTest"
            });
            backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
            backgroundJobs.Schedule(() => ss(), TimeSpan.FromSeconds(5));

            RecurringJob.AddOrUpdate("客户端", () => Console.WriteLine("定时执行5" + DateTime.Now), "*/5 * * * * *");
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/", async context =>
                {
                    backgroundJobs.Enqueue(() => Console.WriteLine("新型智能"));
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }