/// <summary> /// Starts the asynchronous. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> public void CreateJobs() { if (emailRepository.Enabled == false) { return; } Dictionary <string, string> Keys = CronExprs.GetPairs(); emailRepository.GetSchedules().Select(s => s.Key).ToList().ForEach(item => { string expr = item; logger.LogInformation("Adding Schedule for {0}", item); if (Keys.ContainsKey(expr)) { expr = Keys[expr]; } IJobDetail job = JobBuilder.Create <EmailJob>() .WithIdentity(expr, item).Build(); var trigger = TriggerBuilder.Create() .WithIdentity(expr, item).WithCronSchedule(expr) .ForJob(expr, item).Build(); scheduler.ScheduleJob(job, trigger); }); }
/// <summary> /// Executes this instance. /// </summary> /// <returns>Task.</returns> private async Task Execute() { try { lock (syncLock) { DateTime offset = DateTime.UtcNow.AddYears(-1); var key = context.JobDetail.Key.Name; var group = context.JobDetail.Key.Group; var users = emailRepository.GetScheduleById(group); if (users == null) { return; //no one to send this to } if (users.Count > 0) { offset = users.Last().LastSent; } var stories = newsRepository.GetStoriesByDate(offset.AddDays(0)).ToList(); if (stories.Count == 0) { return; } var userList = emailRepository.GetUsers(group); var config = emailRepository.CloneConfiguration(group); var mail = Map.MailConfiguration(config, w => w.Enabled); mail.Body = Map.StoryView(stories).MailMessage(); mail.Subject = "Crypto News Alert"; logger.LogInformation("Executing job {0} - Last Scan: {1} - Users: {2} - Stories: {3}", CronExprs.GetDescription(context.JobDetail.Key.Name), offset, users.Count, stories.Count); logger.LogInformation("Emailing {0} stories {1}", stories.Count, userList); if (config.SmtpClient == "RestSmtp") { var response = RestEmail.SendEmail(mail, config.RestSmtp); logger.LogInformation($"Rest Call ResponseCode: {response?.StatusCode}"); } else { using (SmtpClient client = Map.SmtpClient(config.Smtp)) { logger.LogInformation("Emailing {0} stories {1}", stories.Count, userList); client.Send(mail); logger.LogInformation("Email Sent!"); } } logger.LogInformation("Email Sent!"); users.ForEach(user => user.LastSent = DateTime.UtcNow); emailRepository.SaveChanges(); } } catch (Exception ex) { logger.LogError(1, ex, "An error occurred during execution of scheduled job"); } await Task.FromResult(0); }