Example #1
0
        public async Task <bool> Cancel(int id)
        {
            var record = await _dbService.GetBaseData(id);

            if (record != null)
            {
                //await _dbService.UpdateStatus(record.Id, JobStatus.Cancelled, null);

                if (record.IsFireAndForgetOrScheduled())
                {
                    _bgClient.Delete(record.HfJobId);
                }
                else if (record.IsRecurringJob())
                {
                    var job = JobStorage.Current
                              .GetConnection()
                              .GetRecurringJobs()
                              .FirstOrDefault(x => x.Id == record.HfJobId);

                    if (job != null)
                    {
                        _bgClient.Delete(job.LastJobId);
                    }
                }
                else
                {
                    throw new Exception("Cannot cancel, invalid job type detected.");
                }

                return(true);
            }

            return(false);
        }
Example #2
0
        public async Task <bool> CancelAsync(string id)
        {
            SyncJobEntity job = await _jobs.DeleteAsync(
                j => j.Id == id && SyncJobEntity.ActiveStates.Contains(j.State));

            if (job != null)
            {
                _backgroundJobClient.Delete(job.BackgroundJobId);
                return(true);
            }

            return(false);
        }
Example #3
0
 private void Reset()
 {
     _cancellationTokenSource.Dispose();
     _cancellationTokenSource = null;
     _jobClient.Delete(_jobId);
     _jobId = null;
 }
Example #4
0
 public void CancelScheduledNotification(params Event[] events)
 {
     foreach (var jobId in events.Where(evt => evt.NotificationScheduleJobId != null).Select(evt => evt.NotificationScheduleJobId))
     {
         _backgroundJobClient.Delete(jobId);
     }
 }
            public async Task <Unit> Handle(DeleteFileEntryCommand request, CancellationToken cancellationToken)
            {
                FileEntry fileEntry = await _dbContext.FileEntries.FindAsync(new object[] { request.Id.Value }, cancellationToken);

                if (fileEntry == null)
                {
                    throw new Exception();
                }

                FileInfo fi   = new FileInfo(fileEntry.Path);
                string   path = "/mnt/share";

                if (fi.Exists && fi.Directory.FullName.Equals(path))
                {
                    fi.Delete();
                }

                _dbContext.FileEntries.Remove(fileEntry);

                await _dbContext.SaveChangesAsync(cancellationToken);

                _jobClient.Delete(fileEntry.GenerateSchemaJobId);

                return(Unit.Value);
            }
        private async Task WaitUntilJobCompletedAsync(string jobId, int maxWaitInMilliseconds = 5000)
        {
            IMonitoringApi monitoringApi = JobStorage.Current.GetMonitoringApi();

            var           sw         = Stopwatch.StartNew();
            JobDetailsDto jobDetails = null;

            while ((jobDetails == null || jobDetails.History.All(s => s.StateName != "Succeeded")) && (sw.Elapsed.TotalMilliseconds < maxWaitInMilliseconds || Debugger.IsAttached))
            {
                await Task.Delay(25);

                jobDetails = monitoringApi.JobDetails(jobId);
                if (monitoringApi.FailedCount() > 0)
                {
                    break;
                }
            }

            FailedJobDto failedJob = monitoringApi
                                     .FailedJobs(0, int.MaxValue)
                                     .Select(j => j.Value)
                                     .FirstOrDefault();

            if (failedJob != null)
            {
                throw new InvalidOperationException($"Job failed: {failedJob.ExceptionDetails}.");
            }

            _client.Delete(jobId);
        }
Example #7
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 #8
0
        public void CountParrot(string userId, string channelId, DateTime currentTime)
        {
            var coffeeBreak = _coffeeRepository.GetCoffeeBreak();

            var timeZoneInfo = TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Eastern Standard Time") ?
                               TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") :
                               TimeZoneInfo.FindSystemTimeZoneById("America/New_York");

            var timezoneOffset = timeZoneInfo.GetUtcOffset(currentTime);
            var morningBreak   = TimeSpan.FromHours(MorningBreak) - timezoneOffset;
            var afternoonBreak = TimeSpan.FromHours(AfternoonBreak) - timezoneOffset;

            var morningBreakIsPossible   = IsInTimespan(currentTime, morningBreak, Tolerance);
            var afternoonBreakIsPossible = IsInTimespan(currentTime, afternoonBreak, Tolerance);
            var isTooCloseFromLastBreak  = currentTime < coffeeBreak.LastCoffee + TimeSpan.FromHours(1);

            if (!morningBreakIsPossible && !afternoonBreakIsPossible)
            {
                return;
            }

            if (isTooCloseFromLastBreak || coffeeBreak.IsCoffeeBreak)
            {
                return;
            }

            _coffeeRepository.ConfirmUserReady(userId);

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

            var remindJob = _coffeeRepository.GetRemindJob();

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

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

            _coffeeRepository.SetRemindJob(newRemindJob);
        }
        bool TryRemoveJob(IStorageConnection connection, string id, out string jobId)
        {
            Dictionary <string, string> items = connection.GetAllEntriesFromHash(id);

            if (items != null)
            {
                return(items.TryGetValue(JobIdKey, out jobId) && _backgroundJobClient.Delete(jobId));
            }
            jobId = null;
            return(false);
        }
Example #10
0
        public string EnqueueWithHighPriority <T>(Expression <Action <T> > methodCall, string originalJobId = null)
        {
            var state    = new EnqueuedState(HangfireConstants.HighPriorityQueue);
            var newJobId = _backgroundJobClient.Create(methodCall, state);

            if (originalJobId != null)
            {
                _backgroundJobClient.Delete(originalJobId);
            }

            return(newJobId);
        }
Example #11
0
        public void UnscheduleJob(string identity)
        {
            var job = QueryJobs().FirstOrDefault(x => GetJobModel(x.Job).GetIdentity() == identity);

            if (job == null)
            {
                return;
            }

            _backgroundJobClient.Delete(job.Id);
            _recurringJobManager.RemoveIfExists(job.Id);
        }
Example #12
0
        public string Build()
        {
            try
            {
                // CREATING
                _buildAtom(this);

                // CREATED
                CreateAtomState();

                // RUN
                _client.ChangeState(_atomId, _initialState);
            }
            catch
            {
                // FULL CLEANUP IN CASE OF FAIL
                foreach (var createdJobId in _createdSubAtoms)
                {
                    _client.Delete(createdJobId.Key);
                }

                using (var connection = _jobStorage.GetJobStorageConnection())
                {
                    using var tr = connection.CreateJobStorageTransaction();
                    tr.RemoveSet(Atom.GenerateSubAtomKeys(_atomId));
                    var atomRemainingKeys = Atom.GenerateSubAtomRemainingKeys(_atomId);
                    foreach (var activeSubatoms in _createdSubAtoms.Where(x => !x.Value.IsFinal))
                    {
                        tr.RemoveFromSet(atomRemainingKeys, activeSubatoms.Key);
                    }
                    tr.Commit();
                }

                _client.Delete(_atomId);
                throw;
            }

            return(_atomId);
        }
        public static void UnscheduleJobWhenAlreadyExists(this IBackgroundJobClient backgroundJobClient, RunHangfireWorkflowJobModel data)
        {
            var identity        = data.GetIdentity();
            var monitor         = JobStorage.Current.GetMonitoringApi();
            var workflowJobType = typeof(RunHangfireWorkflowJob);

            var jobs = monitor.ScheduledJobs(0, int.MaxValue)
                       .Where(x => x.Value.Job.Type == workflowJobType && ((RunHangfireWorkflowJobModel)x.Value.Job.Args[0]).GetIdentity() == identity);

            foreach (var job in jobs)
            {
                backgroundJobClient.Delete(job.Key);
            }
        }
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 static void UnscheduleJobWhenAlreadyExists(this IBackgroundJobClient backgroundJobClient, string workflowDefinitionId, string?tenantId)
        {
            var monitor         = JobStorage.Current.GetMonitoringApi();
            var workflowJobType = typeof(RunHangfireWorkflowJob);

            var jobs = monitor.ScheduledJobs(0, int.MaxValue)
                       .Where(x =>
            {
                var model = (RunHangfireWorkflowJobModel)x.Value.Job.Args[0];
                return(x.Value.Job.Type == workflowJobType && model.WorkflowDefinitionId == workflowDefinitionId && model.TenantId == tenantId);
            });

            foreach (var job in jobs)
            {
                backgroundJobClient.Delete(job.Key);
            }
        }
Example #16
0
    public void ClearPendingJobs()
    {
        _logger.LogInformation("Starting clear pending Jobs..");

        var monitor = JobStorage.Current.GetMonitoringApi();
        var queues  = monitor.Queues();

        _logger.LogInformation("Found {QueueCount} queues to delete", queues.Count);

        queues.ForEach(
            dto =>
            dto.FirstJobs.ForEach(
                job => _backgroundJobClient.Delete(job.Key)
                )
            );

        _logger.LogInformation("Clear pending Jobs done!");
    }
Example #17
0
        public async Task <ApiResult> DeleteAsync(int courseId, int userId)
        {
            var result        = default(ApiResult);
            var message       = "Unsabscribe has failed";
            var errors        = new string[] { $"{message}. Contact administrator, please" };
            var loggerMessage = $"{message}. CourseId = {courseId}, UserId = {userId}";

            var courseJobs = await courseJobUser.GetEntitiesByCondition(x => x.CourseId.Equals(courseId) && x.UserId.Equals(userId))
                             .ToArrayAsync();

            if (!courseJobs.Any())
            {
                result = ApiResult.GetErrorResult(ApiResultStatus.BadRequest, loggerMessage, message, errors);
            }
            else
            {
                var removeJobResult = false;
                foreach (var courseJob in courseJobs)
                {
                    removeJobResult = backgroundJobClient.Delete(courseJob.JobId);

                    if (removeJobResult)
                    {
                        await courseJobUser.DeleteAsync(courseJob);
                    }
                    else
                    {
                        result = ApiResult.GetErrorResult(ApiResultStatus.BadRequest, loggerMessage, message, errors);
                        return(result);
                    }
                }


                var userCourse = await usersCourses.GetEntityByConditionAsync(x => x.SystemUserId.Equals(userId) && x.TrainingCourseId.Equals(courseId));

                await usersCourses.DeleteAsync(userCourse);

                result = ApiResult.GetOkResult(ApiResultStatus.Ok);
            }

            return(result);
        }
        private async Task RestartAGame(StartGameResponse result)
        {
            _logger.LogInformation("Attempting to restart a game");

            var battle = await _battleRepository.GetInProgressBattleAsync();

            if (battle is null)
            {
                result.ErrorMessages.Add("There is no battle in progress.");
            }
            else
            {
                _jobClient.Delete(battle.JobId);
                await _battleRepository.UpdateBattleAsync(battle.Id, Entities.Enums.BattleStatus.Initializing);

                _jobClient.Schedule <IGameService>(x => x.StartGameAsync(null, battle.Id), TimeSpan.FromSeconds(1));

                result.BattleId = battle.Id;
            }
        }
Example #19
0
        public async Task <bool> EndBenchmarkExperiment(BenchmarkExperiment benchmarkExperiment)
        {
            Guard.Against.Null(benchmarkExperiment, nameof(benchmarkExperiment));

            benchmarkExperiment.Completed   = true;
            benchmarkExperiment.CompletedAt = DateTimeOffset.UtcNow;
            await _appTestRepo.UpdateAsync(benchmarkExperiment);

            await SetHostToInactive(benchmarkExperiment.Host);
            await SetHostToInactive(benchmarkExperiment.BenchmarkHost);

            if (benchmarkExperiment.DatabaseHost != null)
            {
                await SetHostToInactive(benchmarkExperiment.BenchmarkHost);
            }

            _backgroungJobClient.Delete(benchmarkExperiment.HangfireContainerMetricsJobId);
            await ProcessDockerStats(benchmarkExperiment.Id);

            return(true);
        }
Example #20
0
        public bool CancelJob(string jobId)
        {
            var result = jobClient.Delete(jobId);

            return(result);
        }
Example #21
0
 private void DeleteScheduledJob(string jobId) => _backgroundJobClient.Delete(jobId);
Example #22
0
 /// <summary>
 /// ยกเลิกงาน
 /// </summary>
 /// <param name="jobsId">รหัสงาน</param>
 /// <returns></returns>
 public async Task <bool> DeleteJobsAsync(string jobsId)
 {
     _backgroundJobClient.Delete(jobsId);
     return(true);
 }
Example #23
0
 public Task EndJobAsync(string jobId) => Task.FromResult(_backgroundJobClient.Delete(jobId));
Example #24
0
 private void StopProjectProcessingJob(Project entity)
 {
     _jobClient.Delete(entity.JobId);
 }
        public async Task <CrowdactionResult> UpdateCrowdaction(UpdatedCrowdaction updatedCrowdaction, CancellationToken token)
        {
            logger.LogInformation("Validating updated crowdaction");

            IEnumerable <ValidationResult> validationResults = ValidationHelper.Validate(updatedCrowdaction, serviceProvider);

            if (validationResults.Any())
            {
                return(new CrowdactionResult(validationResults));
            }

            ApplicationUser?owner = await userManager.FindByIdAsync(updatedCrowdaction.OwnerId).ConfigureAwait(false);

            if (owner == null && updatedCrowdaction.OwnerId != null)
            {
                return(new CrowdactionResult(new ValidationResult("New user owner does not exist")));
            }

            Crowdaction?crowdaction = await context
                                      .Crowdactions
                                      .Include(c => c.Tags).ThenInclude(t => t.Tag)
                                      .Include(c => c.Categories)
                                      .FirstOrDefaultAsync(c => c.Id == updatedCrowdaction.Id, token).ConfigureAwait(false);

            if (crowdaction == null)
            {
                return(new CrowdactionResult(new ValidationResult("Crowdaction not found", new[] { nameof(Crowdaction.Id) })));
            }

            if (crowdaction.Name != updatedCrowdaction.Name && await context.Crowdactions.AnyAsync(c => c.Name == updatedCrowdaction.Name, token).ConfigureAwait(false))
            {
                return(new CrowdactionResult(new ValidationResult("A crowdaction with this name already exists", new[] { nameof(Crowdaction.Name) })));
            }

            logger.LogInformation("Updating crowdaction: {0}", updatedCrowdaction.Name);

            bool approved        = updatedCrowdaction.Status == CrowdactionStatus.Running && crowdaction.Status != CrowdactionStatus.Running;
            bool changeFinishJob = (approved || crowdaction.End != updatedCrowdaction.End) && updatedCrowdaction.End > DateTime.UtcNow;
            bool removeFinishJob = updatedCrowdaction.Status != CrowdactionStatus.Running && crowdaction.FinishJobId != null;
            bool deleted         = updatedCrowdaction.Status == CrowdactionStatus.Deleted;

            crowdaction.Name                        = updatedCrowdaction.Name;
            crowdaction.Description                 = updatedCrowdaction.Description;
            crowdaction.Proposal                    = updatedCrowdaction.Proposal;
            crowdaction.Goal                        = updatedCrowdaction.Goal;
            crowdaction.CreatorComments             = updatedCrowdaction.CreatorComments;
            crowdaction.Target                      = updatedCrowdaction.Target;
            crowdaction.Start                       = updatedCrowdaction.Start;
            crowdaction.End                         = updatedCrowdaction.End.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
            crowdaction.BannerImageFileId           = updatedCrowdaction.BannerImageFileId;
            crowdaction.CardImageFileId             = updatedCrowdaction.CardImageFileId;
            crowdaction.DescriptiveImageFileId      = updatedCrowdaction.DescriptiveImageFileId;
            crowdaction.DescriptionVideoLink        = updatedCrowdaction.DescriptionVideoLink?.Replace("www.youtube.com", "www.youtube-nocookie.com", StringComparison.Ordinal);
            crowdaction.Status                      = updatedCrowdaction.Status;
            crowdaction.DisplayPriority             = updatedCrowdaction.DisplayPriority;
            crowdaction.NumberCrowdactionEmailsSent = updatedCrowdaction.NumberCrowdactionEmailsSent;
            crowdaction.OwnerId                     = updatedCrowdaction.OwnerId;
            context.Crowdactions.Update(crowdaction);

            var crowdactionTags = crowdaction.Tags.Select(t => t.Tag !.Name);
            var tags            = updatedCrowdaction.Tags.Distinct().ToList();

            if (!Enumerable.SequenceEqual(tags.OrderBy(t => t), crowdactionTags.OrderBy(t => t)))
            {
                IEnumerable <string> missingTags =
                    tags.Except(await context.Tags
                                .Where(t => tags.Contains(t.Name))
                                .Select(t => t.Name)
                                .ToListAsync(token).ConfigureAwait(false));

                if (missingTags.Any())
                {
                    context.Tags.AddRange(missingTags.Select(t => new Tag(t)));
                    await context.SaveChangesAsync(token).ConfigureAwait(false);
                }

                var tagMap =
                    await context.Tags
                    .Where(t => tags.Contains(t.Name) || crowdactionTags.Contains(t.Name))
                    .ToDictionaryAsync(t => t.Name, t => t.Id, token).ConfigureAwait(false);

                IEnumerable <CrowdactionTag> newTags =
                    tags.Except(crowdactionTags)
                    .Select(t => new CrowdactionTag(crowdactionId: crowdaction.Id, tagId: tagMap[t]));

                IEnumerable <CrowdactionTag> removedTags =
                    crowdaction.Tags
                    .Where(t => crowdactionTags.Except(tags).Contains(t.Tag !.Name));
                context.CrowdactionTags.AddRange(newTags);
                context.CrowdactionTags.RemoveRange(removedTags);
            }

            var categories = crowdaction.Categories.Select(c => c.Category);

            if (!Enumerable.SequenceEqual(categories.OrderBy(c => c), updatedCrowdaction.Categories.OrderBy(c => c)))
            {
                IEnumerable <Category>            newCategories     = updatedCrowdaction.Categories.Except(categories);
                IEnumerable <CrowdactionCategory> removedCategories = crowdaction.Categories.Where(pc => !updatedCrowdaction.Categories.Contains(pc.Category));

                context.CrowdactionCategories.RemoveRange(removedCategories);
                context.CrowdactionCategories.AddRange(newCategories.Select(c => new CrowdactionCategory(crowdactionId: crowdaction.Id, category: c)));
            }

            if (approved && owner != null)
            {
                await emailSender.SendEmailTemplated(owner.Email, $"Approval - {crowdaction.Name}", "CrowdactionApproval").ConfigureAwait(false);
            }
            else if (deleted && owner != null)
            {
                await emailSender.SendEmailTemplated(owner.Email, $"Deleted - {crowdaction.Name}", "CrowdactionDeleted").ConfigureAwait(false);
            }

            if (changeFinishJob)
            {
                if (crowdaction.FinishJobId != null)
                {
                    jobClient.Delete(crowdaction.FinishJobId);
                }

                crowdaction.FinishJobId = jobClient.Schedule(() => CrowdactionEndProcess(crowdaction.Id, CancellationToken.None), crowdaction.End);
            }
            else if (removeFinishJob)
            {
                jobClient.Delete(crowdaction.FinishJobId);
            }

            await context.SaveChangesAsync(token).ConfigureAwait(false);

            logger.LogInformation("Updated crowdaction: {0}", updatedCrowdaction.Name);

            return(new CrowdactionResult(crowdaction));
        }
Example #26
0
 public bool Delete(string jobId)
 {
     return(_client.Delete(jobId));
 }
Example #27
0
 public bool Delete(string jobId) => _client.Delete(jobId);
 private void CancelJob(PropertyReference <ScheduledJobInfo> jobInfoReference, IBackgroundJobClient jobClient)
 {
     jobClient.Delete(jobInfoReference.Value.JobId);
     _db.ScheduledJobInfos.Remove(jobInfoReference.Value);
     jobInfoReference.Value = null;
 }