public RecurringJobsPage() { RecurringJobs = new List <RecurringJobDto>(); using (var connection = JobStorage.Current.GetConnection()) { var ids = connection.GetAllItemsFromSet("recurring-jobs"); foreach (var id in ids) { var hash = connection.GetAllEntriesFromHash(String.Format("recurring-job:{0}", id)); if (hash == null) { RecurringJobs.Add(new RecurringJobDto { Id = id, Removed = true }); continue; } var dto = new RecurringJobDto { Id = id }; dto.Cron = hash["Cron"]; try { var invocationData = JobHelper.FromJson <InvocationData>(hash["Job"]); dto.Job = invocationData.Deserialize(); } catch (JobLoadException ex) { dto.LoadException = ex; } if (hash.ContainsKey("NextExecution")) { dto.NextExecution = JobHelper.DeserializeDateTime(hash["NextExecution"]); } if (hash.ContainsKey("LastJobId")) { dto.LastJobId = hash["LastJobId"]; var stateData = connection.GetStateData(dto.LastJobId); if (stateData != null) { dto.LastJobState = stateData.Name; } } if (hash.ContainsKey("LastExecution")) { dto.LastExecution = JobHelper.DeserializeDateTime(hash["LastExecution"]); } RecurringJobs.Add(dto); } } }
public void AddTwoJobsAndRemoveOne() { // Mock: var recurringJobManager = Substitute.For <IRecurringJobManager>(); var jobStorage = Substitute.For <JobStorage>(); var recurringJobRepositoryMock = Substitute.For <RecurringJobRepository>(jobStorage); var recurringJobs = new List <RecurringJobDto>(); var recurringJobDto = new RecurringJobDto { Id = "jobToRemove" }; recurringJobs.Add(recurringJobDto); recurringJobRepositoryMock.GetRecurringJobs().Returns(recurringJobs); // Arrange var hourly = Cron.Hourly(); Expression <Action <string> > methodCall = text => text.ToString(); var recurringJobCleanUpManager = new RecurringJobCleanUpManager(recurringJobManager, recurringJobRepositoryMock) { EnforceRecurringJob.Create("jobrecurrent", methodCall, hourly), EnforceRecurringJob.Create("jobrecurrent2", methodCall, hourly) }; // Act recurringJobCleanUpManager.AddUpdateDeleteJobs(); // Assert recurringJobManager.Received() .AddOrUpdate("jobrecurrent", Arg.Any <Job>(), hourly, Arg.Any <RecurringJobOptions>()); recurringJobManager.Received() .AddOrUpdate("jobrecurrent2", Arg.Any <Job>(), hourly, Arg.Any <RecurringJobOptions>()); recurringJobManager.Received().RemoveIfExists("jobToRemove"); }
private JobBO MapEntityToModel(RecurringJobDto source) { if (source == null) { return(null); } JobBO job = (JobBO)source.Job.Args.ToList().FirstOrDefault(rec => rec.GetType().Name == "JobBO"); if (job != null) { job.Id = int.Parse(source.Id); job.LastFinishedDateTime = source.LastExecution; job.Cron = source.Cron; job.Status = source.LastJobState; return(job); } return(new JobBO { Id = int.Parse(source.Id), Cron = source.Cron, LastFinishedDateTime = source.LastExecution, Status = source.LastJobState }); }
public static void CreateRecurringJob <T>(string jobName, Expression <Func <T, Task> > methodCall, string cronSchedule = null, string queue = "default") { // override if jobName is available in the settings file. string cronOverride = CronFromConfig(jobName); cronSchedule = (!string.IsNullOrEmpty(cronOverride)) ? cronOverride : cronSchedule ??= Cron.Daily(22, 30); var connection = JobStorage.Current.GetConnection(); Globals.DefaultConfiguration.GetSection(jobName); RecurringJob.AddOrUpdate <T>( recurringJobId: jobName, methodCall: methodCall, cronExpression: cronSchedule, timeZone: TimeZoneInfo.Local, queue: queue); RecurringJobDto newJob = connection.GetRecurringJobs(new string[] { jobName }).First(); if (newJob.LastExecution is null) { RecurringJob.Trigger(jobName); } }
private static ZonedDateTime GetJobsZonedDateTime(RecurringJobDto rJobDto, DateTimeZone hostDTZ) { LocalDateTime ldt = LocalDateTime.FromDateTime(rJobDto.NextExecution !.Value); ZonedDateTime zdt = ldt.InUtc(); zdt = zdt.WithZone(hostDTZ); return(zdt); }
public static RecurringJobDto JobFromId(string id) { RecurringJobDto job = Hangfire.JobStorage.Current.GetConnection() .GetRecurringJobs() .FirstOrDefault(p => p.Id == id); return(job); }
public RecurringJobsPage() { RecurringJobs = new List<RecurringJobDto>(); using (var connection = JobStorage.Current.GetConnection()) { var ids = connection.GetAllItemsFromSet("recurring-jobs"); foreach (var id in ids) { var hash = connection.GetAllEntriesFromHash(String.Format("recurring-job:{0}", id)); if (hash == null) { RecurringJobs.Add(new RecurringJobDto { Id = id, Removed = true }); continue; } var dto = new RecurringJobDto { Id = id }; dto.Cron = hash["Cron"]; try { var invocationData = JobHelper.FromJson<InvocationData>(hash["Job"]); dto.Job = invocationData.Deserialize(); } catch (JobLoadException ex) { dto.LoadException = ex; } if (hash.ContainsKey("NextExecution")) { dto.NextExecution = JobHelper.DeserializeDateTime(hash["NextExecution"]); } if (hash.ContainsKey("LastJobId")) { dto.LastJobId = hash["LastJobId"]; var stateData = connection.GetStateData(dto.LastJobId); if (stateData != null) { dto.LastJobState = stateData.Name; } } if (hash.ContainsKey("LastExecution")) { dto.LastExecution = JobHelper.DeserializeDateTime(hash["LastExecution"]); } RecurringJobs.Add(dto); } } }
public object GetSettings(string id) { RecurringJobDto job = HangfireJobForm.JobFromId(id); HangfireJobForm result = null; if (job != null) { result = new HangfireJobForm(job); } return(result); }
public HangfireJobForm(RecurringJobDto job) { Id = job.Id; Name = ((HangfireJob[])job.Job.Method.GetCustomAttributes(typeof(HangfireJob), false)).Length > 0 ? ((HangfireJob[])job.Job.Method.GetCustomAttributes(typeof(HangfireJob), false))[0].Name : "Untitled"; Cron = job.Cron; CronNum = new HangfireNumMod(job.Cron).Num; CronMod = new HangfireNumMod(job.Cron).ModToString(); State = (job.LastJobState ?? "None"); LastExecuted = GetLocalDateString(job.LastExecution); NextExecution = GetLocalDateString(job.NextExecution); }
private bool IsNotProcessing() { d = hangfireStorage.GetRecurringJobs().Where(x => x.Id == "DBF_Connector.BackgroundTask").FirstOrDefault(); var tmp = d?.LastJobState; if (tmp != "Processing") { return(true); } else { return(false); } }
public object ExecuteNow(HangfireJobForm data) { RecurringJobManager manager = new RecurringJobManager(); RecurringJobDto job = HangfireJobForm.JobFromId(data.Id); manager.Trigger(job.Id); job = HangfireJobForm.JobFromId(data.Id); return(new { data.Id, job.Cron, Success = true, Message = "Hangfire job is now queued for execution.", LastExecuted = HangfireJobForm.GetLocalDateString(job.LastExecution), NextExecution = HangfireJobForm.GetLocalDateString(job.NextExecution) }); }
/// <summary> /// Generate the embed with the randomly selected movies and add emojis to allow for voting /// </summary> /// <param name="movieNightId">ID for the movie night in the data store</param> /// <exception cref="ArgumentException">Thrown when an unknown movie night ID is provided</exception> public async Task StartVoting(int movieNightId) { GuildMovieNight movieNight = await GetGuildMovieNightAsync(movieNightId); (DiscordClient client, DiscordGuild guild, DiscordChannel channel) = await this.GetCommonDiscordObjects(movieNight); DbResult <IEnumerable <GuildMovieSuggestion> > randomSuggestionsResult = await this .mediator.Send(new GuildMovieSuggestions.GetRandomGuildMovieSuggestions(guild, movieNight.NumberOfSuggestions, movieNight.MaximumRating)); if (!randomSuggestionsResult.TryGetValue(out IEnumerable <GuildMovieSuggestion>?randomSuggestions)) { throw new Exception("Something went wrong with getting the random suggestions."); } string description = AddMovieSuggestionsAndGenerateDescription(client, movieNight, randomSuggestions); RecurringJobDto rJobDto = GetMovieNightStartRecurringJobInfo(movieNight); DateTimeZone hostDTZ = await GetUserDateTimeZone(movieNight.HostId); ZonedDateTime zdt = GetJobsZonedDateTime(rJobDto, hostDTZ); DiscordEmbed eBuilder = new DiscordEmbedBuilder() .WithTitle($"Time to vote for a movie!") .WithDescription(description) .AddField("Date and Time of Movie", zdt.ToString("MM/dd/yyyy hh:mm x", null), true) .AddField("Maximum Parental Rating", movieNight.MaximumRating.ToQueryValue(), true); DiscordMessageBuilder mBuilder = new DiscordMessageBuilder() .WithContent("@everyone") .WithEmbed(eBuilder); DiscordMessage votingMessage = await channel.SendMessageAsync(mBuilder); movieNight.VotingMessageId = votingMessage.Id; await this.mediator.Send(new GuildMovieNights.Update(movieNight)); foreach (DiscordEmoji emoji in GetNumberEmojis(client).Take(randomSuggestions.Count())) { await votingMessage.CreateReactionAsync(emoji); } }
/// <summary> /// Determine the number of votes that each movie got and then select the highest ranked movie. /// If there is a tie on more than one of the movies, message the movie night creator with an /// embed where they will break the tie. /// </summary> /// <param name="movieNightId">ID for the movie night in the data store</param> public async Task CalculateVotes(int movieNightId) { GuildMovieNight movieNight = await GetGuildMovieNightAsync(movieNightId); (DiscordClient client, DiscordGuild guild, DiscordChannel channel) = await this.GetCommonDiscordObjects(movieNight); DiscordMessage votingMessage = await channel.GetMessageAsync(movieNight.VotingMessageId ?? throw new Exception("Somehow, some way, the voting message id was null... something done f$*@ed up.")); Dictionary <string, DiscordReaction> mostReactedReactions = GetMostReactedReactons(votingMessage); DiscordMember host = await guild.GetMemberAsync(movieNight.HostId); GuildMovieSuggestion winningSuggestion = await GetWinningSuggestion(client, guild, host, movieNight, mostReactedReactions); movieNight.WinningMovieImdbId = winningSuggestion.ImdbId; DbResult movieNightUpdateResult = await this.mediator.Send(new GuildMovieNights.Update(movieNight)); if (!movieNightUpdateResult.Success) { throw new Exception("An error occurred in updating the movie night with the winning suggestion"); } RecurringJobDto rJobDto = GetMovieNightStartRecurringJobInfo(movieNight); LocalDateTime ldt = LocalDateTime.FromDateTime(rJobDto.NextExecution !.Value); DateTimeZone hostDTZ = await GetUserDateTimeZone(movieNight.HostId); ZonedDateTime zdt = ldt.InUtc(); zdt = zdt.WithZone(hostDTZ); OmdbMovie movieInfo = await this.omdbClient.GetByImdbIdAsync(winningSuggestion.ImdbId, omdbPlotOption : OmdbPlotOption.SHORT); DiscordEmbedBuilder announceWinnerEmbed = movieInfo.ToDiscordEmbedBuilder(true) .WithAuthor(host.DisplayName, iconUrl: host.AvatarUrl); DiscordMessageBuilder announceWinnerMessage = new DiscordMessageBuilder() .WithContent($"@everyone, here's what {host.Mention} is showing {zdt.ToString("MM/dd/yyyy hh:mm x", null)}") .WithEmbed(announceWinnerEmbed.Build()); await channel.SendMessageAsync(announceWinnerMessage); }
public virtual BackgroundJobModel PrepareBackgroundJobModel(RecurringJobDto job, HashSet <string> pausedJobs) { var result = new BackgroundJobModel(); if (job == null) { return(result); } result.Id = job.Id; result.Job = job.Job.ToString(); result.TimeZoneId = job.TimeZoneId; result.Cron = job.Cron; result.NextExecution = job.NextExecution?.ToLocalTime().ToString("F") ?? "-"; result.LastExecution = job.LastExecution?.ToLocalTime().ToString("F") ?? "-"; result.LastExecutionState = job.LastJobState; result.LastJobId = job.LastJobId; result.CronDesc = ExpressionDescriptor.GetDescription(job.Cron); result.Paused = pausedJobs.Contains(job.Id); return(result); }
public object Save(HangfireJobForm data) { RecurringJobManager manager = new RecurringJobManager(); RecurringJobDto job = HangfireJobForm.JobFromId(data.Id); manager.RemoveIfExists(data.Id); manager.AddOrUpdate(data.Id, job.Job, data.Cron, TimeZoneInfo.Local); job = HangfireJobForm.JobFromId(data.Id); while (job.NextExecution == null) { // Wait for the update to be stored in Hangfire's database System.Threading.Thread.Sleep(2000); job = HangfireJobForm.JobFromId(data.Id); } return(new { Success = true, Message = "Settings were saved successfully!", LastExecuted = HangfireJobForm.GetLocalDateString(job.LastExecution), NextExecution = HangfireJobForm.GetLocalDateString(job.NextExecution) }); }
public abstract string ToString(RecurringJobDto job, SocketTextChannel channel);
public override string ToString(RecurringJobDto job, SocketTextChannel channel) { return($"{job.Id}: search '{Tags}' on e621 into {channel.Mention} {job.Cron.ToCronDescription()}"); }
public static RecurringJobDto GetRecurringJobDto(this IStorageConnection connection, string recurringJobId) { var hash = connection.GetAllEntriesFromHash($"recurring-job:{recurringJobId}"); if (hash == null) { return(null); } var dto = new RecurringJobDto { Id = recurringJobId, Cron = hash["Cron"] }; try { if (hash.TryGetValue("Job", out var payload) && !String.IsNullOrWhiteSpace(payload)) { var invocationData = InvocationData.DeserializePayload(payload); dto.Job = invocationData.DeserializeJob(); } } catch (JobLoadException ex) { dto.LoadException = ex; } if (hash.ContainsKey("NextExecution")) { dto.NextExecution = JobHelper.DeserializeNullableDateTime(hash["NextExecution"]); } if (hash.ContainsKey("LastJobId") && !string.IsNullOrWhiteSpace(hash["LastJobId"])) { dto.LastJobId = hash["LastJobId"]; var stateData = connection.GetStateData(dto.LastJobId); if (stateData != null) { dto.LastJobState = stateData.Name; } } if (hash.ContainsKey("Queue")) { dto.Queue = hash["Queue"]; } if (hash.ContainsKey("LastExecution")) { dto.LastExecution = JobHelper.DeserializeNullableDateTime(hash["LastExecution"]); } if (hash.ContainsKey("TimeZoneId")) { dto.TimeZoneId = hash["TimeZoneId"]; } if (hash.ContainsKey("CreatedAt")) { dto.CreatedAt = JobHelper.DeserializeNullableDateTime(hash["CreatedAt"]); } if (hash.TryGetValue("Error", out var error)) { dto.Error = error; } return(dto); }
public override string ToString(RecurringJobDto job, SocketTextChannel channel) { return($"{job.Id}: execute '{Command}' in {channel.Mention} {job.Cron.ToCronDescription()}"); }