/// <summary> /// Executes this instance. /// </summary> /// <param name="message"></param> public override void Execute(Message message) { using (var rockContext = new RockContext()) { var jobService = new ServiceJobService(rockContext); var job = jobService.Get(message.JobId); if (job == null) { return; } jobService.RunNow(job, out _); } }
/// <summary> /// Deletes the job. /// </summary> /// <param name="jobId">The job identifier.</param> public static void DeleteJob(int jobId) { using (var rockContext = new RockContext()) { var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); if (job != null) { jobService.Delete(job); rockContext.SaveChanges(); return; } } }
/// <summary> /// Binds the scheduled jobs. /// </summary> private void BindGrid() { ServiceJobService jobService = new ServiceJobService(); SortProperty sortProperty = gScheduledJobs.SortProperty; if (sortProperty != null) { gScheduledJobs.DataSource = jobService.GetActiveJobs().Sort(sortProperty).ToList(); } else { gScheduledJobs.DataSource = jobService.GetActiveJobs().OrderByDescending(a => a.LastRunDateTime).ToList(); } gScheduledJobs.DataBind(); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; // get the configured timeout, or default to 60 minutes if it is blank var commandTimeout = dataMap.GetString(AttributeKey.CommandTimeout).AsIntegerOrNull() ?? 3600; var migrationHelper = new MigrationHelper(new JobMigration(commandTimeout)); migrationHelper.DropIndexIfExists("Interaction", "IX_InteractionComponentId_InteractionDateTime"); migrationHelper.CreateIndexIfNotExists("Interaction", new[] { "InteractionComponentId", "InteractionDateTime" }, new[] { "InteractionTimeToServe", "Operation", "InteractionSessionId" }); ServiceJobService.DeleteJob(context.GetJobId()); }
/// <summary> /// Binds the scheduled jobs. /// </summary> private void BindGrid() { var jobService = new ServiceJobService(new RockContext()); SortProperty sortProperty = gScheduledJobs.SortProperty; if (sortProperty != null) { gScheduledJobs.DataSource = jobService.GetAllJobs().Sort(sortProperty).ToList(); } else { gScheduledJobs.DataSource = jobService.GetAllJobs().OrderByDescending(a => a.LastRunDateTime).ThenBy(a => a.Name).ToList(); } gScheduledJobs.DataBind(); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; // get the configured timeout, or default to 60 minutes if it is blank var commandTimeout = dataMap.GetString(AttributeKey.CommandTimeout).AsIntegerOrNull() ?? 3600; var migrationHelper = new MigrationHelper(new JobMigration(commandTimeout)); migrationHelper.DropIndexIfExists("CommunicationRecipient", "IX_Status"); migrationHelper.CreateIndexIfNotExists("CommunicationRecipient", new[] { "Status" }, new[] { "CommunicationId" }); ServiceJobService.DeleteJob(context.GetJobId()); }
/// <summary> /// Handles the RunNow event of the gScheduledJobs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gScheduledJobs_RunNow(object sender, RowEventArgs e) { var job = new ServiceJobService(new RockContext()).Get(e.RowKeyId); if (job != null) { new ProcessRunJobNow.Message { JobId = job.Id }.Send(); mdGridWarning.Show(string.Format("The '{0}' job has been started.", job.Name), ModalAlertType.Information); // wait a split second for the job to start so that the grid will show the status (if it changed) System.Threading.Tasks.Task.Delay(250).Wait(); } BindGrid(); }
/// <summary> /// Handles the Delete event of the grdScheduledJobs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gScheduledJobs_Delete(object sender, RowEventArgs e) { ServiceJobService jobService = new ServiceJobService(); ServiceJob job = jobService.Get((int)e.RowKeyValue); string errorMessage; if (!jobService.CanDelete(job, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } jobService.Delete(job, CurrentPersonId); jobService.Save(job, CurrentPersonId); BindGrid(); }
/// <summary> /// Updates the LastStatusMessage of the Rock Job associated with the IJobExecutionContext /// </summary> /// <param name="context">The context.</param> /// <param name="message">The message.</param> public static void UpdateLastStatusMessage(this Quartz.IJobExecutionContext context, string message) { // save the message to context.Result so that RockJobListener will set the save the same message when the Job completes context.Result = message; int jobId = context.GetJobId(); using (var rockContext = new RockContext()) { var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); if (job != null) { job.LastStatusMessage = message; rockContext.SaveChanges(); } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { ServiceJob job; var rockContext = new RockContext(); ServiceJobService jobService = new ServiceJobService(rockContext); int jobId = int.Parse(hfId.Value); if (jobId == 0) { job = new ServiceJob(); jobService.Add(job); } else { job = jobService.Get(jobId); } job.Name = tbName.Text; job.Description = tbDescription.Text; job.IsActive = cbActive.Checked; job.Class = ddlJobTypes.SelectedValue; job.NotificationEmails = tbNotificationEmails.Text; job.NotificationStatus = (JobNotificationStatus)int.Parse(ddlNotificationStatus.SelectedValue); job.CronExpression = tbCronExpression.Text; if (!job.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { rockContext.SaveChanges(); job.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, job); job.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
/// <summary> /// Handles the Delete event of the grdScheduledJobs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gScheduledJobs_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var jobService = new ServiceJobService(rockContext); ServiceJob job = jobService.Get(e.RowKeyId); string errorMessage; if (!jobService.CanDelete(job, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } jobService.Delete(job); rockContext.SaveChanges(); BindGrid(); }
protected override void OnStart(string[] args) { ISchedulerFactory sf; // create scheduler sf = new StdSchedulerFactory(); sched = sf.GetScheduler(); // get list of active jobs ServiceJobService jobService = new ServiceJobService(); foreach (ServiceJob job in jobService.GetActiveJobs().ToList()) { try { IJobDetail jobDetail = jobService.BuildQuartzJob(job); ITrigger jobTrigger = jobService.BuildQuartzTrigger(job); sched.ScheduleJob(jobDetail, jobTrigger); } catch (Exception ex) { // get path to the services directory String path = System.Reflection.Assembly.GetExecutingAssembly().Location; path = System.IO.Path.GetDirectoryName(path); // create a friendly error message string message = string.Format("Error loading the job: {0}. Ensure that the correct version of the job's assembly ({1}.dll) in the services directory ({2}) of your server.", job.Name, job.Assembly, path); message = message + "\n\n\n\n" + ex.Message; //throw new JobLoadFailedException( message ); job.LastStatusMessage = message; job.LastStatus = "Error Loading Job"; jobService.Save(job, null); } } // set up the listener to report back from jobs as they complete sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs()); // start the scheduler sched.Start(); }
/// <summary> /// Handles the RunNow event of the gScheduledJobs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gScheduledJobs_RunNow(object sender, RowEventArgs e) { var job = new ServiceJobService(new RockContext()).Get(e.RowKeyId); if (job != null) { var transaction = new Rock.Transactions.RunJobNowTransaction(job.Id); // Process the transaction on another thread System.Threading.Tasks.Task.Run(() => transaction.Execute()); mdGridWarning.Show(string.Format("The '{0}' job has been started.", job.Name), ModalAlertType.Information); // wait a split second for the job to start so that the grid will show the status (if it changed) System.Threading.Thread.Sleep(250); } BindGrid(); }
public void RemoveTestJob() { if (testJobId == 0) { return; } using (var rockContext = new RockContext()) { var serviceJobService = new ServiceJobService(rockContext); var testJob = serviceJobService.Get(testJobId); if (testJob == null) { return; } serviceJobService.Delete(testJob); rockContext.SaveChanges(); } }
/// <summary> /// Called by the <see cref="IScheduler"/> when a <see cref="IJobDetail"/> /// is about to be executed (an associated <see cref="ITrigger"/> /// has occurred). /// <para> /// This method will not be invoked if the execution of the Job was vetoed /// by a <see cref="ITriggerListener"/>. /// </para> /// </summary> /// <param name="context"></param> /// <seealso cref="JobExecutionVetoed(IJobExecutionContext)"/> public void JobToBeExecuted(IJobExecutionContext context) { StringBuilder message = new StringBuilder(); // get job type id int jobId = context.JobDetail.Description.AsInteger(); // load job var rockContext = new RockContext(); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); if (job != null && job.Guid != Rock.SystemGuid.ServiceJob.JOB_PULSE.AsGuid()) { job.LastStatus = "Running"; job.LastStatusMessage = "Started at " + RockDateTime.Now.ToString(); rockContext.SaveChanges(); } }
/// <summary> /// Transform the web.config to inject system.diagnostics configuration and save related system settings. /// </summary> /// <returns>true if the transform was successful; false otherwise.</returns> private bool SaveSystemDiagnosticsSettings() { var adoNetPerformanceCountersAreEnabled = cbEnableAdoNetPerformanceCounters.Checked; var transformSb = new StringBuilder(@"<?xml version='1.0'?> <configuration xmlns:xdt='http://schemas.microsoft.com/XML-Document-Transform'> <system.diagnostics xdt:Transform='InsertIfMissing'> <switches xdt:Transform='InsertIfMissing'> <add name='ConnectionPoolPerformanceCounterDetail' xdt:Transform='RemoveAll' xdt:Locator='Match(name)' />"); if (adoNetPerformanceCountersAreEnabled) { transformSb.Append(@" <add name='ConnectionPoolPerformanceCounterDetail' value='4' xdt:Transform='Insert' />"); } transformSb.Append(@" </switches> </system.diagnostics> </configuration>"); if (!TransformWebConfig(transformSb.ToString())) { return(false); } // Update the "core_EnableAdoNetPerformanceCounters" System Setting Rock.Web.SystemSettings.SetValue(SystemSetting.SYSTEM_DIAGNOSTICS_ENABLE_ADO_NET_PERFORMANCE_COUNTERS, adoNetPerformanceCountersAreEnabled.ToString()); // Toggle the "Collect Hosting Metrics" ServiceJob's IsActive status if necessary var rockContext = new RockContext(); var serviceJob = new ServiceJobService(rockContext).Get(Rock.SystemGuid.ServiceJob.COLLECT_HOSTING_METRICS.AsGuid()); if (serviceJob != null && serviceJob.IsActive != adoNetPerformanceCountersAreEnabled) { serviceJob.IsActive = !serviceJob.IsActive; rockContext.SaveChanges(); } return(true); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(IJobExecutionContext context) { var familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; var rockContext = new RockContext(); // just in case there are Groups that have a null or empty Name, update them. var familiesWithoutNames = new GroupService(rockContext) .Queryable().Where(a => a.GroupTypeId == familyGroupTypeId) .Where(a => string.IsNullOrEmpty(a.Name)); if (familiesWithoutNames.Any()) { rockContext.BulkUpdate(familiesWithoutNames, g => new Group { Name = "Family" }); } // Re-calculates all GroupSalutation values on Family Groups. var familyIdList = new GroupService(rockContext) .Queryable().Where(a => a.GroupTypeId == familyGroupTypeId) .Select(a => a.Id).ToList(); foreach (var familyId in familyIdList) { try { using (var rockContextUpdate = new RockContext()) { GroupService.UpdateGroupSalutations(familyId, rockContextUpdate); } } catch (Exception ex) { ExceptionLogService.LogException(new Exception($"Error running the job 'PostV127DataMigrationsRebuildGroupSalutations'. UpdateGroupSalutations failed for Group Id {familyId}", ex)); } } ServiceJobService.DeleteJob(context.GetJobId()); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { ServiceJob job; ServiceJobService jobService = new ServiceJobService(); int jobId = int.Parse(hfId.Value); if (jobId == 0) { job = new ServiceJob(); jobService.Add(job, CurrentPersonId); } else { job = jobService.Get(jobId); } job.Name = tbName.Text; job.Description = tbDescription.Text; job.IsActive = cbActive.Checked; job.Assembly = tbAssembly.Text; job.Class = tbClass.Text; job.NotificationEmails = tbNotificationEmails.Text; job.NotificationStatus = (JobNotificationStatus)int.Parse(drpNotificationStatus.SelectedValue); job.CronExpression = tbCronExpression.Text; if (!job.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { jobService.Save(job, CurrentPersonId); }); BindGrid(); pnlDetails.Visible = false; pnlGrid.Visible = true; }
/// <summary> /// Handles the SelectedIndexChanged event of the ddlJobTypes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void ddlJobTypes_SelectedIndexChanged(object sender, EventArgs e) { ServiceJob job; var itemId = PageParameter("serviceJobId").AsInteger(); if (itemId == 0) { job = new ServiceJob { Id = 0, IsActive = true }; } else { job = new ServiceJobService(new RockContext()).Get(itemId); } job.Class = ddlJobTypes.SelectedValue; job.LoadAttributes(); phAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls(job, phAttributes, true, BlockValidationGroup); }
/// <summary> /// Handles the CheckedChanged event when enabling/disabling the NCOA option. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void cbNcoaConfiguration_CheckedChanged(object sender, EventArgs e) { _sparkDataConfig = Ncoa.GetSettings(); _sparkDataConfig.NcoaSettings.IsEnabled = cbNcoaConfiguration.Checked; Rock.Web.SystemSettings.SetValue(SystemSetting.SPARK_DATA, _sparkDataConfig.ToJson()); // Save job active status using (var rockContext = new RockContext()) { var ncoaJob = new ServiceJobService(rockContext).Get(Rock.SystemGuid.ServiceJob.GET_NCOA.AsGuid()); if (ncoaJob != null) { ncoaJob.IsActive = cbNcoaConfiguration.Checked; rockContext.SaveChanges(); } } SetPanels(); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> /// <exception cref="System.NotImplementedException"></exception> public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; int howMany = dataMap.GetString("HowMany").AsIntegerOrNull() ?? 300000; var commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600; CommunicationSchemaUpdates(); bool anyRemaining = UpdateCommunicationRecords(true, howMany, commandTimeout); if (!anyRemaining) { // Verify that there are not any communication records with medium data. using (var rockContext = new RockContext()) { rockContext.Database.CommandTimeout = commandTimeout; // if there is any v6 MediumDataJson data, it would be have a datalength of 2 or more (blank would be null, '', or '{}') if (!new CommunicationService(rockContext) .Queryable() .Where(c => SqlFunctions.DataLength(c.MediumDataJson) > 2) .Any()) { // delete job if there are no PageView or CommunicationRecipientActivity rows left var jobId = context.GetJobId(); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); if (job != null) { jobService.Delete(job); rockContext.SaveChanges(); return; } } } } }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> /// <exception cref="System.NotImplementedException"></exception> public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; int howMany = dataMap.GetString("HowMany").AsIntegerOrNull() ?? 300000; CommunicationSchemaUpdates(); bool anyRemaining = UpdateCommunicationRecords(true, howMany); if (!anyRemaining) { // Verify that there are not any communication records with medium data. using (var rockContext = new RockContext()) { if (!new CommunicationService(rockContext) .Queryable() .Where(c => c.MediumDataJson != null && c.MediumDataJson != "" && c.MediumDataJson != "{}") .Any()) { // delete job if there are no PageView or CommunicationRecipientActivity rows left var jobId = context.GetJobId(); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); if (job != null) { jobService.Delete(job); rockContext.SaveChanges(); return; } } } } }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> /// <exception cref="System.NotImplementedException"></exception> public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; CommunicationPendingCommunicationMediumEntityTypeFix(); bool canDeleteJob = true; if (canDeleteJob) { // Verify that there are not any communication records with medium data. using (var rockContext = new RockContext()) { var jobId = context.GetJobId(); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); if (job != null) { jobService.Delete(job); rockContext.SaveChanges(); return; } } } }
/// <summary> /// Handles the SaveClick event of the mdRunNcoa control. This is the Start NCOA dialog. Save = Start /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void mdRunNcoa_SaveClick(object sender, EventArgs e) { Ncoa ncoa = new Ncoa(); var sparkDataConfig = Ncoa.GetSettings(); sparkDataConfig.NcoaSettings.PersonFullName = CurrentPerson != null ? CurrentPerson.FullName : null; sparkDataConfig.NcoaSettings.CurrentReportStatus = "Start"; Ncoa.SaveSettings(sparkDataConfig); using (RockContext rockContext = new RockContext()) { ServiceJob job = new ServiceJobService(rockContext).Get(Rock.SystemGuid.ServiceJob.GET_NCOA.AsGuid()); if (job != null) { new ProcessRunJobNow.Message { JobId = job.Id }.Send(); mdGridWarning.Show(string.Format("The '{0}' job has been started.", job.Name), ModalAlertType.Information); lbStartNcoa.Enabled = false; } } mdRunNcoa.Hide(); }
public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var JobGuid = GetAttributeValue(action, "Job").AsGuid(); if (!JobGuid.IsEmpty()) { ServiceJob Job = new ServiceJobService(rockContext).Get(JobGuid); if (Job != null) { new ProcessRunJobNow.Message { JobId = Job.Id }.Send(); action.AddLogEntry(string.Format("The '{0}' job has been started.", Job.Name)); return(true); } } errorMessages.Add("The specified Job could not be found"); return(false); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { try { ExpressionDescriptor.GetDescription(tbCronExpression.Text); } catch (Exception ex) { tbCronExpression.ShowErrorMessage("Invalid Cron Expression: " + ex.Message); return; } ServiceJob job; var rockContext = new RockContext(); ServiceJobService jobService = new ServiceJobService(rockContext); int jobId = int.Parse(hfId.Value); if (jobId == 0) { job = new ServiceJob(); jobService.Add(job); } else { job = jobService.Get(jobId); } job.Name = tbName.Text; job.Description = tbDescription.Text; job.IsActive = cbActive.Checked; if (job.Class != ddlJobTypes.SelectedValue) { job.Class = ddlJobTypes.SelectedValue; //// if the Class has changed, the current Assembly value might not match, //// so set the Assembly to null to have Rock figure it out automatically job.Assembly = null; } job.NotificationEmails = tbNotificationEmails.Text; job.NotificationStatus = (JobNotificationStatus)int.Parse(ddlNotificationStatus.SelectedValue); job.CronExpression = tbCronExpression.Text; if (!job.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); job.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, job); job.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="serviceJobId">The service job identifier.</param> public void ShowDetail(int serviceJobId) { pnlDetails.Visible = true; LoadDropDowns(); // Load depending on Add(0) or Edit ServiceJob job = null; if (!serviceJobId.Equals(0)) { job = new ServiceJobService(new RockContext()).Get(serviceJobId); lActionTitle.Text = ActionTitle.Edit(ServiceJob.FriendlyTypeName).FormatAsHtmlTitle(); } if (job == null) { job = new ServiceJob { Id = 0, IsActive = true }; lActionTitle.Text = ActionTitle.Add(ServiceJob.FriendlyTypeName).FormatAsHtmlTitle(); } hfId.Value = job.Id.ToString(); tbName.Text = job.Name; tbDescription.Text = job.Description; cbActive.Checked = job.IsActive.HasValue ? job.IsActive.Value : false; ddlJobTypes.SelectedValue = job.Class; tbNotificationEmails.Text = job.NotificationEmails; ddlNotificationStatus.SetValue((int)job.NotificationStatus); tbCronExpression.Text = job.CronExpression; if (job.Id == 0) { job.Class = ddlJobTypes.SelectedValue; lCronExpressionDesc.Visible = false; lLastStatusMessage.Visible = false; } else { lCronExpressionDesc.Text = ExpressionDescriptor.GetDescription(job.CronExpression, new Options { ThrowExceptionOnParseError = false }); lCronExpressionDesc.Visible = true; lLastStatusMessage.Text = job.LastStatusMessage.ConvertCrLfToHtmlBr(); lLastStatusMessage.Visible = true; } job.LoadAttributes(); phAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls(job, phAttributes, true, BlockValidationGroup); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(ServiceJob.FriendlyTypeName); } if (job.IsSystem) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(ServiceJob.FriendlyTypeName); } if (readOnly) { lActionTitle.Text = ActionTitle.View(ServiceJob.FriendlyTypeName).FormatAsHtmlTitle(); btnCancel.Text = "Close"; Rock.Attribute.Helper.AddDisplayControls(job, phAttributesReadOnly); phAttributesReadOnly.Visible = true; phAttributes.Visible = false; tbCronExpression.Text = job.CronExpression; } tbName.ReadOnly = readOnly; tbDescription.ReadOnly = readOnly; cbActive.Enabled = !readOnly; ddlJobTypes.Enabled = !readOnly; tbNotificationEmails.ReadOnly = readOnly; ddlNotificationStatus.Enabled = !readOnly; tbCronExpression.ReadOnly = readOnly; btnSave.Visible = !readOnly; }
public void RunJob(Dictionary <string, string> jobDataMapDictionary, JobNotificationStatus jobNotificationStatus = JobNotificationStatus.None) { var job = GetAddTestJob(jobNotificationStatus); using (var rockContext = new RockContext()) { var jobService = new ServiceJobService(rockContext); if (job != null) { // create a scheduler specific for the job var scheduleConfig = new System.Collections.Specialized.NameValueCollection(); var runNowSchedulerName = ("RunNow:" + job.Guid.ToString("N")).Truncate(40); scheduleConfig.Add(StdSchedulerFactory.PropertySchedulerInstanceName, runNowSchedulerName); var schedulerFactory = new StdSchedulerFactory(scheduleConfig); var sched = new StdSchedulerFactory(scheduleConfig).GetScheduler(); if (sched.IsStarted) { // the job is currently running as a RunNow job return; } // Check if another scheduler is running this job try { var otherSchedulers = new Quartz.Impl.StdSchedulerFactory().AllSchedulers .Where(s => s.SchedulerName != runNowSchedulerName); foreach (var scheduler in otherSchedulers) { if (scheduler.GetCurrentlyExecutingJobs().Where(j => j.JobDetail.Description == job.Id.ToString() && j.JobDetail.ConcurrentExectionDisallowed).Any()) { // A job with that Id is already running and ConcurrentExectionDisallowed is true System.Diagnostics.Debug.WriteLine(RockDateTime.Now.ToString() + $" Scheduler '{scheduler.SchedulerName}' is already executing job Id '{job.Id}' (name: {job.Name})"); return; } } } catch { } // create the quartz job and trigger IJobDetail jobDetail = jobService.BuildQuartzJob(job); if (jobDataMapDictionary != null) { // Force the <string, string> dictionary so that within Jobs, it is always okay to use // JobDataMap.GetString(). This mimics Rock attributes always being stored as strings. // If we allow non-strings, like integers, then JobDataMap.GetString() throws an exception. jobDetail.JobDataMap.PutAll(jobDataMapDictionary.ToDictionary(kvp => kvp.Key, kvp => ( object )kvp.Value)); } var jobTrigger = TriggerBuilder.Create() .WithIdentity(job.Guid.ToString(), job.Name) .StartNow() .Build(); // schedule the job sched.ScheduleJob(jobDetail, jobTrigger); // set up the listener to report back from the job when it completes sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs()); // start the scheduler sched.Start(); // Wait 10secs to give job chance to start System.Threading.Tasks.Task.Delay(new TimeSpan(0, 0, 10)).Wait(); // stop the scheduler when done with job sched.Shutdown(true); } } }
/// <summary> /// Called by the <see cref="IScheduler"/> after a <see cref="IJobDetail"/> /// has been executed, and before the associated <see cref="Quartz.Spi.IOperableTrigger"/>'s /// <see cref="Quartz.Spi.IOperableTrigger.Triggered"/> method has been called. /// </summary> /// <param name="context"></param> /// <param name="jobException"></param> public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException) { StringBuilder message = new StringBuilder(); bool sendMessage = false; // get job type id int jobId = Convert.ToInt16(context.JobDetail.Description); // load job ServiceJobService jobService = new ServiceJobService(); ServiceJob job = jobService.Get(jobId); // format the message message.Append(String.Format("The job {0} ran for {1} seconds on {2}. Below is the results:<p>", job.Name, context.JobRunTime.TotalSeconds, context.FireTimeUtc.Value.DateTime.ToLocalTime())); // if noticiation staus is all set flag to send message if (job.NotificationStatus == JobNotificationStatus.All) { sendMessage = true; } // set last run date job.LastRunDateTime = context.FireTimeUtc.Value.DateTime.ToLocalTime(); // set run time job.LastRunDurationSeconds = Convert.ToInt32(context.JobRunTime.TotalSeconds); // set the scheduler name job.LastRunSchedulerName = context.Scheduler.SchedulerName; // determine if an error occured if (jobException == null) { job.LastSuccessfulRunDateTime = job.LastRunDateTime; job.LastStatus = "Success"; job.LastStatusMessage = ""; message.Append("Result: Success"); // determine if message should be sent if (job.NotificationStatus == JobNotificationStatus.Success) { sendMessage = true; } } else { // put the exception into the status job.LastStatus = "Exception"; job.LastStatusMessage = jobException.Message; message.Append("Result: Exception<p>Message:<br>" + jobException.Message); if (jobException.InnerException != null) { job.LastStatusMessage += " Inner Exception: " + jobException.InnerException.Message; message.Append("<p>Inner Exception:<br>" + jobException.InnerException.Message); } if (job.NotificationStatus == JobNotificationStatus.Error) { sendMessage = true; } } jobService.Save(job, null); // send notification if (sendMessage) { // TODO: implement email send once it's available } }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var rockContext = new RockContext(); InteractionChannelService channelService = new InteractionChannelService(rockContext); InteractionComponentService componentService = new InteractionComponentService(rockContext); InteractionService interactionService = new InteractionService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); LocationService locationService = new LocationService(rockContext); AttendanceService attendanceService = new AttendanceService(rockContext); GroupService groupService = new GroupService(rockContext); // Load the channel InteractionChannelCache channel = InteractionChannelCache.Read(dataMap.GetString("InteractionChannel").AsGuid()); // Setup int campusLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS).Id; var groupType = GroupTypeCache.Read(dataMap.GetString("GroupType").AsGuid()); var groups = groupService.GetByGroupTypeId(groupType.Id); string operation = !string.IsNullOrWhiteSpace(dataMap.GetString("Operation")) ? dataMap.GetString("Operation") : null; // Fetch the job so we can get the last run date/time int jobId = Convert.ToInt16(context.JobDetail.Description); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); DateTime lastRun = job?.LastSuccessfulRunDateTime ?? DateTime.MinValue; var componentCampusMapping = dataMap.GetString("ComponentCampusMapping").AsDictionaryOrNull(); foreach (var componentName in componentCampusMapping.Keys) { var component = componentService.Queryable().Where(cs => cs.Name.ToLower() == componentName.ToLower() && cs.ChannelId == channel.Id).FirstOrDefault(); CampusCache campus = CampusCache.All().Where(c => c.Name == componentCampusMapping[componentName]).FirstOrDefault(); if (campus != null && component != null) { Group group = groups.Where(g => g.IsActive == true && g.CampusId == campus.Id).FirstOrDefault(); if (group?.GroupLocations != null) { foreach (var gl in group?.GroupLocations) { Location location = gl.Location; foreach (Schedule schedule in gl.Schedules) { var occurrences = schedule.GetOccurrences(DateTime.MinValue, DateTime.Now); foreach (var occurrence in occurrences) { DateTime startDate = occurrence.Period.StartTime.Value; DateTime endDate = occurrence.Period.EndTime.Value; var peopleAttended = interactionService.Queryable().Where( i => i.InteractionComponentId == component.Id && i.InteractionDateTime <= endDate && i.InteractionEndDateTime >= startDate && i.PersonAliasId != null && (i.CreatedDateTime > lastRun || i.PersonalDevice.ModifiedDateTime > lastRun || i.PersonalDevice.CreatedDateTime > lastRun) && (operation == null || i.Operation == operation) ).Select(i => i.PersonAliasId).Distinct(); int newAttendance = 0; foreach (int personAliasId in peopleAttended) { // Make sure we don't already have an attendance Record if (!attendanceService.Queryable().Any(a => DbFunctions.TruncateTime(a.StartDateTime) == occurrence.Period.StartTime.Value.Date && a.ScheduleId == schedule.Id && a.PersonAliasId == personAliasId && a.GroupId == group.Id && a.LocationId == location.Id && a.DidAttend == true)) { Attendance attendance = new Attendance() { PersonAliasId = personAliasId, CampusId = campus.Id, GroupId = group.Id, LocationId = location.Id, ScheduleId = schedule.Id, StartDateTime = occurrence.Period.StartTime.Value, EndDateTime = occurrence.Period?.EndTime?.Value, DidAttend = true }; attendanceService.Add(attendance); newAttendance++; } } if (newAttendance > 0) { rockContext.SaveChanges(); context.Result += string.Format("{0} people attended {1} on {2} (Component {3}).\n", newAttendance, campus.Name, occurrence.Period.StartTime.Value.ToString("MM/dd/yyyy h:mm tt"), component.Name); } } } } } } } }