public void UpdateScheduleTasks(NotificationsPart notification) { var schedulingPart = notification.As <SchedulingPart>(); // TODO: this can (should) never happen, throw error? if (schedulingPart == null || !schedulingPart.StartDateTime.HasValue) { return; } // Remove existing schedules DeleteExistingScheduleTasks(schedulingPart.ContentItem); // Event started task _scheduledTaskManager.CreateTask(Constants.EventStartedName, schedulingPart.StartDateTime.Value, schedulingPart.ContentItem); // Event ended task if (schedulingPart.EndDateTime.HasValue) { _scheduledTaskManager.CreateTask(Constants.EventEndedName, schedulingPart.EndDateTime.Value, schedulingPart.ContentItem); } else if (schedulingPart.IsAllDay) { // If event is all day, end time is start time + 1 day var endTime = schedulingPart.StartDateTime.Value.Date.AddDays(1); _scheduledTaskManager.CreateTask(Constants.EventEndedName, endTime, schedulingPart.ContentItem); } // TODO: schedule upcoming and followup }
public ActionResult CreateAndSend(int newsletterId) { //if (!Services.Authorizer.Authorize(Permissions.ManageNewsletterDefinitions, T("Couldn't create newsletter"))) // return new HttpUnauthorizedResult(); var newsletterEdition = Services.ContentManager.New <NewsletterEditionPart>("NewsletterEdition"); var returnResult = EditionSave(ref newsletterEdition); if (returnResult == null) { if (Request.Form["submit.SendNewsletter"] == "submit.SendNewsletterTest") { //_newslServices.SendNewsletterEdition(ref newsletterEdition, true, Request.Form["Newsletters.SendNewsletterEmailTest"]); _newslServices.SendNewsletterEdition(ref newsletterEdition, Request.Form["Newsletters.SendNewsletterEmailTest"]); } else { //_newslServices.SendNewsletterEdition(ref newsletterEdition); ContentItem newsletter = newsletterEdition.ContentItem; _taskManager.CreateTask("Laser.Orchard.NewsLetters.SendEdition.Task", DateTime.UtcNow.AddMinutes(1), newsletter); } return(Redirect(Url.NewsLetterEditionEdit(newsletterId, newsletterEdition))); } else { return(returnResult); } }
public void Sweep() { var peddingTaskCount = _repository.Count(x => x.ScheduledUtc > _clock.UtcNow && x.TaskType == "ResetSite" || x.ScheduledUtc > _clock.UtcNow && x.TaskType == "SwitchTheme"); if (peddingTaskCount == 0) { _themeService.EnableThemeFeatures("Mooncake"); _siteThemeService.SetSiteTheme("Mooncake"); _scheduledTaskManager.CreateTask("SwitchTheme", _clock.UtcNow.AddMinutes(29), null); _scheduledTaskManager.CreateTask("ResetSite", _clock.UtcNow.AddMinutes(30), null); } }
public void Process(ScheduledTaskContext context) { if (context.Task.TaskType != Constants.CleanupSnapshots) { return; } try { var idsToRetain = new List <int>(); foreach (var retentionPolicy in _retentionPolicies) { idsToRetain.AddRange(retentionPolicy.GetSnapshotIdsToRetain()); } var recordsToDelete = _repository.Table.Where(r => !idsToRetain.Contains(r.Id)); foreach (var record in recordsToDelete) { _repository.Delete(record); } } catch (Exception ex) { Logger.Error(ex, "Failed to cleanup Content Sync Snapshots. An exception was thrown by the task handler."); } //now reschedule the task _scheduledTaskManager.DeleteTasks(null, a => a.TaskType == Constants.CleanupSnapshots); _scheduledTaskManager.CreateTask(Constants.CleanupSnapshots, _clock.UtcNow.AddMinutes(1), null); }
public override IEnumerable <TemplateViewModel> PartFieldEditorUpdate( ContentPartFieldDefinitionBuilder builder, IUpdateModel updateModel) { if (builder.FieldType == "HiddenStringField") { var model = new HiddenStringFieldSettingsEventsViewModel { Settings = new HiddenStringFieldSettings(), ProcessVariant = HiddenStringFieldUpdateProcessVariant.None, ProcessVariants = GetVariants() }; if (updateModel.TryUpdateModel(model, "HiddenStringFieldSettingsEventsViewModel", null, null)) { builder.WithSetting("HiddenStringFieldSettings.Tokenized", model.Settings.Tokenized.ToString()); builder.WithSetting("HiddenStringFieldSettings.TemplateString", model.Settings.TemplateString); builder.WithSetting("HiddenStringFieldSettings.AutomaticAdjustmentOnEdit", model.Settings.AutomaticAdjustmentOnEdit.ToString()); if (model.ProcessVariant != HiddenStringFieldUpdateProcessVariant.None) { // TODO: Check task isn't already scheduled. var completeFieldName = _contentTypeName + "_" + builder.PartName + "_" + builder.Name + "_" + model.ProcessVariant.ToString(); _scheduledTaskManager.CreateTask(HiddenStringFieldValueUpdateTaskHandler.UPDATEVALUES_TASK + "_" + completeFieldName, _clock.UtcNow.AddMinutes(1), null); } model.ProcessVariant = HiddenStringFieldUpdateProcessVariant.None; yield return(DefinitionTemplate(model)); } } else { yield break; } }
public void Process(ScheduledTaskContext context) { if (context.Task.TaskType != Constants.TakeSnapshotTaskName) { return; } try { //the default export service impl makes an assumption that there is an associated user, so we need to set the owner here var siteOwner = _membershipService.GetUser(_orchardServices.WorkContext.CurrentSite.As <SiteSettingsPart>().SuperUser); _authenticationService.SetAuthenticatedUserForRequest(siteOwner); _snapshotService.TakeSnaphot(); } catch (Exception ex) { Logger.Error(ex, "Failed to generate a scheduled Content Sync Snapshot. An exception was thrown by the task handler."); } //now reschedule the task _scheduledTaskManager.DeleteTasks(null, a => a.TaskType == Constants.TakeSnapshotTaskName); var snapshotFrequency = _orchardServices.WorkContext.CurrentSite.As <ContentSyncSettingsPart>().SnapshotFrequencyMinutes; if (snapshotFrequency == 0) { return; } _scheduledTaskManager.CreateTask(Constants.TakeSnapshotTaskName, _clock.UtcNow.AddMinutes(snapshotFrequency), null); }
public void Process(ScheduledTaskContext context) { // We have a task for each type that requires scheduled processing. We could have done // this differently, by having a task for each ContentItem. The processing for each of // those would have been lighter. However, changes in the configuration for this task // would have been much harder to handle. string taskTypeStr = context.Task.TaskType; if (taskTypeStr.IndexOf(Constants.ScheduledTaskName) == 0) { // by splitting the string we should get a type name. To be safe, we do ElementAtOrDefault var typeName = taskTypeStr .Split(new string[] { "_" }, 2, StringSplitOptions.RemoveEmptyEntries) .ElementAtOrDefault(1); if (!string.IsNullOrWhiteSpace(typeName)) { // get the settings for the type var settings = _contentDefinitionManager.GetTypeDefinition(typeName) .Parts .FirstOrDefault(ctpd => ctpd.PartDefinition.Name == "GDPRPart") ?.Settings ?.GetModel <GDPRPartTypeSchedulingSettings>() ?? new GDPRPartTypeSchedulingSettings(); if (settings.ScheduleAnonymization) { Process( typeName, settings.EventForAnonymization, settings.AnonymizationDaysToWait, _contentGDPRManager.Anonymize, context.Task.ContentItem == null); // this being null means the task was not created here } if (settings.ScheduleErasure) { Process( typeName, settings.EventForErasure, settings.ErasureDaysToWait, _contentGDPRManager.Erase, context.Task.ContentItem == null); } if (settings.ScheduleAnonymization || settings.ScheduleErasure) { // reschedule _taskManager.CreateTask( taskTypeStr, // "same" task _clock.UtcNow + TimeSpan.FromDays(1), // one day from now _siteService.GetSiteSettings().ContentItem // pass a ContentItem. ); // passing a ContentItem there to the new task allows us to discriminate, when we are processing it, // over whether the task being processed was created here or in the other service. This allows us to // better filter over things in the query. } } } }
public void ScheduleNextTask(Int32 minute, ContentItem ci) { if (minute > 0) { DateTime date = DateTime.UtcNow.AddMinutes(minute); _scheduledTaskManager.CreateTask(TaskType, date, ci); } }
public DynamicButtonToWorkflowsPartHandler( INotifier notifier, IScheduledTaskManager scheduledTaskManager, IWorkflowManager workflowManager) { _notifier = notifier; _scheduledTaskManager = scheduledTaskManager; T = NullLocalizer.Instance; _workflowManager = workflowManager; OnUpdated <DynamicButtonToWorkflowsPart>((context, part) => { try { if (!string.IsNullOrWhiteSpace(part.ButtonName)) { var content = context.ContentItem; if (part.ActionAsync) { // the task will need to use part.ButtonName to invoke the correct // process. We generate a task that contains that in its type. Then // we will parse that out when processing the task. _scheduledTaskManager .CreateTask( DynamicButtonToWorflowsScheduledTaskHandler.TaskType(part.ButtonName), DateTime.UtcNow.AddMinutes(1), part.ContentItem); if (!string.IsNullOrEmpty(part.MessageToWrite)) { _notifier.Add(NotifyType.Information, T(part.MessageToWrite)); } } else { _workflowManager .TriggerEvent("DynamicButtonEvent", content, () => new Dictionary <string, object> { { "ButtonName", part.ButtonName }, { "Content", content } }); if (!string.IsNullOrEmpty(part.MessageToWrite)) { _notifier.Add(NotifyType.Information, T(part.MessageToWrite)); } } part.ButtonName = ""; part.MessageToWrite = ""; } } catch (Exception ex) { Logger.Error(ex, "Error in DynamicButtonToWorkflowsPartHandler. ContentItem: {0}", context.ContentItem); part.ButtonName = ""; part.MessageToWrite = ""; } }); }
public static void EmailAsync(this IScheduledTaskManager _taskManager, ContentItem contentItem) { var tasks = _taskManager.GetTasks(Services.EmailScheduledTaskHandler.TASK_TYPE_EMAIL); if (tasks == null || tasks.Count() < 100) { _taskManager.CreateTask(Services.EmailScheduledTaskHandler.TASK_TYPE_EMAIL, DateTime.UtcNow, contentItem); } }
public static void AppendModelAsync(this IScheduledTaskManager _taskManager, ContentItem contentItem) { var tasks = _taskManager.GetTasks(Services.AppendModelScheduledTaskHandler.TASK_TYPE_APPEND_MODEL); if (tasks == null || tasks.Count() < 100) { _taskManager.CreateTask(Services.AppendModelScheduledTaskHandler.TASK_TYPE_APPEND_MODEL, DateTime.UtcNow, contentItem); } }
public ActionResult Synchronize() { if (_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner)) { // schedula il task per la sincronizzazione var scheduledSynchronizations = _taskManager.GetTasks(Handlers.SynchronizeContactTaskHandler.TaskType); if (scheduledSynchronizations.Count() == 0) { _taskManager.CreateTask(Handlers.SynchronizeContactTaskHandler.TaskType, DateTime.UtcNow.AddSeconds(5), null); _notifier.Add(NotifyType.Information, T("Synchronization started. Please come back on this page in a few minutes to check the result.")); } else { _notifier.Add(NotifyType.Information, T("Synchronization already scheduled at {0:dd-MM-yyyy HH:mm}. Please come back later on this page to check the result.", DateTime.SpecifyKind(scheduledSynchronizations.Min(x => x.ScheduledUtc).Value, DateTimeKind.Utc).ToLocalTime())); } } return(RedirectToAction("Index", "ContactsAdmin")); }
void IArchiveLaterService.ArchiveLater(ContentItem contentItem, DateTime scheduledArchiveUtc) { if (!Services.Authorizer.Authorize(Permissions.PublishContent, contentItem, T("Couldn't archive selected content."))) { return; } RemoveArchiveLaterTasks(contentItem); _scheduledTaskManager.CreateTask(UnpublishTaskType, scheduledArchiveUtc, contentItem); }
public MobilePushPartHandler(IRepository <MobilePushPartRecord> repository, INotifier notifier, IScheduledTaskManager taskManager, IOrchardServices orchardServices, IPushGatewayService pushGatewayService) { Logger = NullLogger.Instance; T = NullLocalizer.Instance; _notifier = notifier; _orchardServices = orchardServices; _pushGatewayService = pushGatewayService; _taskManager = taskManager; Filters.Add(StorageFilter.For(repository)); OnUpdated <MobilePushPart>((context, part) => { if (_orchardServices.WorkContext.HttpContext.Request.Form["submit.Save"] == "submit.PushTest") { // Invio Push di Test _pushGatewayService.PublishedPushEventTest(part.ContentItem); } if (_orchardServices.WorkContext.HttpContext.Request.Form["submit.Save"] == "submit.PushContact") { // invia la push al contact selezionato string contactTitle = ""; string aux = _orchardServices.WorkContext.HttpContext.Request.Form["contact-to-push"]; // rimuove il numero di device racchiuso tra parentesi per ricavare il nome del contact int idx = aux.LastIndexOf(" ("); if (idx > 0) { contactTitle = aux.Substring(0, idx); } else { contactTitle = aux; } // invia la push if ((string.IsNullOrWhiteSpace(contactTitle) == false) && (string.IsNullOrWhiteSpace(part.TextPush) == false)) { _pushGatewayService.SendPushToContact(part.ContentItem, contactTitle); _notifier.Information(T("Push message will be sent to contact {0} in a minute.", contactTitle)); } } }); OnPublished <MobilePushPart>((context, part) => { try { if ((part.ToPush == true) && (part.PushSent == false)) { _taskManager.CreateTask("Laser.Orchard.PushNotification.Task", DateTime.UtcNow.AddMinutes(-1), part.ContentItem); part.PushSent = true; } } catch (Exception ex) { Logger.Error(ex, "Error starting asynchronous thread to send push notifications."); } }); }
public void ScheduleEvent(SchedulingPart eventDefinitionPart) { // Delete ongoing schedules // TODO: also the other taskTypes, see Constants -> Scheduling Constants _scheduledTaskManager.DeleteTasks(eventDefinitionPart.ContentItem, task => task.TaskType == Constants.EventStartedName); if (eventDefinitionPart.StartDateTime.HasValue) { _scheduledTaskManager.CreateTask(Constants.EventStartedName, eventDefinitionPart.StartDateTime.Value, eventDefinitionPart.ContentItem); } }
public static void CreateTaskIfNew(this IScheduledTaskManager taskManager, string taskType, DateTime scheduledUtc, ContentItem contentItem) { var outdatedTaskCount = taskManager.GetTasks(taskType, DateTime.UtcNow).Count(); var taskCount = taskManager.GetTasks(taskType).Count(); if (taskCount != 0 && taskCount - outdatedTaskCount > 0) { return; } taskManager.CreateTask(taskType, scheduledUtc, contentItem); }
public void CreateTask(ContentItem item) { var name = TransformalizeTaskHandler.GetName(item.As <TitlePart>().Title); var tasks = _manager.GetTasks(name); if (tasks != null && tasks.Any()) { return; } _manager.CreateTask(name, DateTime.UtcNow.AddSeconds(30), item); }
public ActionResult Settings(UserReactionsTypes model) { if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Yout have to be an Administrator to edit Reaction types settings!"))) { return(new HttpUnauthorizedResult()); } if (!ModelState.IsValid) { _orchardServices.Notifier.Error(T("Settings update failed: {0}", T("check your input!"))); return(View(model)); } var reactionSettings = _orchardServices.WorkContext.CurrentSite.As <UserReactionsSettingsPart>(); reactionSettings.StyleFileNameProvider = model.CssName; reactionSettings.AllowMultipleChoices = model.AllowMultipleChoices; bool newTypesCreated = false; foreach (var item in model.UserReactionsType) { if (item.Id == 0) { var styleAcronime = new Laser.Orchard.UserReactions.StyleAcroName(); string styleAcronimeName = styleAcronime.StyleAcronime + item.TypeName; _repoTypes.Create(new Models.UserReactionsTypesRecord { Priority = item.Priority, TypeName = item.TypeName, Activating = item.Activating }); newTypesCreated = true; } else { var record = _repoTypes.Get(item.Id); record.Priority = item.Priority; record.TypeName = item.TypeName; record.Activating = item.Activating; _repoTypes.Update(record); } } if (newTypesCreated) { // allinea i contenuti tramite un task schedulato _taskManager.CreateTask("Laser.Orchard.UserReactionsSettings.Task", DateTime.UtcNow.AddSeconds(5), null); _notifier.Add(NotifyType.Warning, T("A task has been scheduled to update reaction summaries for existing contents.")); } _notifier.Add(NotifyType.Information, T("UserReaction settings updating")); return(RedirectToActionPermanent("Settings")); }
public void Process(ScheduledTaskContext context) { try { // this.Logger.Error("sono dentro process"); string taskTypeStr = context.Task.TaskType; string[] taTypeParts = taskTypeStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (taTypeParts.Length == 2) { if (taTypeParts[0] == TaskType) { bool sent = false; try { int gId = int.Parse(taTypeParts[1]); sent = _questionnairesServices.SendTemplatedEmailRanking(gId); } catch (Exception e) { this.Logger.Error(e, e.Message); throw; } if (!sent) { //reschedule DateTime nextDate = ((DateTime)(context.Task.ScheduledUtc)).AddMinutes(5); _taskManager.CreateTask(taskTypeStr, nextDate, context.Task.ContentItem); } } } } catch (Exception ex) { string idcontenuto = "nessun id "; try { idcontenuto = context.Task.ContentItem.Id.ToString(); } catch (Exception ex2) { Logger.Error(ex2, ex2.Message); } Logger.Error(ex, "Error on " + TaskType + " analized input: " + context.Task.TaskType + " for ContentItem id = " + idcontenuto + " : " + ex.Message); } //if (context.Task.TaskType == TaskType) { // try { // bool sended= _questionnairesServices.SendTemplatedEmailRanking(); // //The following line does not work here, because the task does not contain the ContentItem // //_questionnairesServices.SendTemplatedEmailRanking(context.Task.ContentItem.Id); // } // catch (Exception e) { // this.Logger.Error(e, e.Message); // } // finally { // DateTime nextTaskDate = DateTime.UtcNow.AddHours(6); //DateTime.UtcNow.AddSeconds(30);// // ScheduleNextTask(nextTaskDate); // } //} }
/// <summary> /// Schedule a new task based on the information in the view model /// </summary> /// <param name="vm">The view model we are basing the new task on</param> public void ScheduleTask(ScheduledTaskViewModel vm) { //get the part ScheduledTaskPart part = (ScheduledTaskPart)_orchardServices.ContentManager.Get <ScheduledTaskPart>(vm.Id); //define tasktype: BASE_SIGNALNAME_ID string taskTypeStr = Constants.TaskTypeBase + "_" + part.SignalName + "_" + part.Id; ContentItem ci = null; if (part.ContentItemId > 0) { ci = _orchardServices.ContentManager.Get(part.ContentItemId); } _taskManager.CreateTask(taskTypeStr, part.ScheduledStartUTC ?? DateTime.UtcNow, ci); part.RunningTaskId = _repoTasks.Get(str => str.TaskType.Equals(taskTypeStr)).Id; }
public DynamicButtonToWorkflowsPartHandler(INotifier notifier, IScheduledTaskManager scheduledTaskManager, IWorkflowManager workflowManager) { _notifier = notifier; _scheduledTaskManager = scheduledTaskManager; _workflowManager = workflowManager; T = NullLocalizer.Instance; OnUpdated <DynamicButtonToWorkflowsPart>((context, part) => { try { if (!string.IsNullOrWhiteSpace(part.ButtonName)) { var content = context.ContentItem; if (part.ActionAsync) { _scheduledTaskManager.CreateTask("Laser.Orchard.DynamicButtonToWorkflows.Task", DateTime.UtcNow.AddMinutes(1), part.ContentItem); if (!string.IsNullOrEmpty(part.MessageToWrite)) { _notifier.Add(NotifyType.Information, T(part.MessageToWrite)); } } else { _workflowManager.TriggerEvent("DynamicButtonEvent", content, () => new Dictionary <string, object> { { "ButtonName", part.ButtonName }, { "Content", content } }); if (!string.IsNullOrEmpty(part.MessageToWrite)) { _notifier.Add(NotifyType.Information, T(part.MessageToWrite)); } part.ButtonName = ""; part.MessageToWrite = ""; part.ActionAsync = false; } } } catch (Exception ex) { Logger.Error(ex, "Error in DynamicButtonToWorkflowsPartHandler. ContentItem: {0}", context.ContentItem); part.ButtonName = ""; part.MessageToWrite = ""; part.ActionAsync = false; } }); }
public ButtonToWorkflowsPartHandler(IWorkflowManager workflowManager, INotifier notifier, IScheduledTaskManager scheduledTaskManager) { _workflowManager = workflowManager; _notifier = notifier; _scheduledTaskManager = scheduledTaskManager; T = NullLocalizer.Instance; OnUpdated <ButtonToWorkflowsPart>((context, part) => { if (!string.IsNullOrEmpty(part.ActionToExecute)) { var content = context.ContentItem; if (part.ActionAsync) { // part.ButtonsDenied = true; _scheduledTaskManager.CreateTask("Laser.Orchard.ButtonToWorkflows.Task", DateTime.UtcNow.AddMinutes(1), part.ContentItem); } else { _workflowManager.TriggerEvent(part.ActionToExecute, content, () => new Dictionary <string, object> { { "Content", content } }); part.MessageToWrite = ""; part.ActionToExecute = ""; part.ActionAsync = false; } try { if (!string.IsNullOrEmpty(part.MessageToWrite)) { _notifier.Add(NotifyType.Information, T(part.MessageToWrite)); } } catch { } } // if (context.ContentItem.As<CommonPart>() != null) { // var currentUser = _orchardServices.WorkContext.CurrentUser; //if (currentUser != null) { // ((dynamic)context.ContentItem.As<CommonPart>()).LastModifier.Value = currentUser.Id; // if (((dynamic)context.ContentItem.As<CommonPart>()).Creator.Value == null) // // ((NumericField) CommonPart.Fields.Where(x=>x.Name=="Creator").FirstOrDefault()).Value = currentUser.Id; // ((dynamic)context.ContentItem.As<CommonPart>()).Creator.Value = currentUser.Id; //} // } }); }
public ActionResult SendNotificationAgain(int id) { Dictionary <string, object> result = new Dictionary <string, object>(); var ci = _orchardServices.ContentManager.Get(id); if (_orchardServices.Authorizer.Authorize(Permissions.PublishContent, ci)) { _pushGatewayService.ResetNotificationFailures(ci); _taskManager.CreateTask("Laser.Orchard.PushNotification.Task", DateTime.UtcNow.AddMinutes(-1), ci); result.Add("result", "ok"); } else { result.Add("result", "ko"); result.Add("error", "Authorization failure"); } return(Json(result)); }
// This helper method creates the task for us but only if is not already in the system. You should be aware that the task type is not a // unique key: multiple tasks with the same type can exist. Thus if there's an uncompleted task in the system already (because e.g. Orchard // was torn down before it could run) simply creating the task would create a new one. This in turn would have the effect that our Process() // method would run for both tasks, resulting in more frequent execution than what we want. private void CreateTaskIfNew(bool calledFromTaskProcess) { var outdatedTaskCount = _taskManager.GetTasks(TaskType, _clock.UtcNow).Count(); var taskCount = _taskManager.GetTasks(TaskType).Count(); // calledFromTaskProcess is necessary as when this is called from Proces() the current task will still be in the DB, thus there // will be at least a single task there. if ((!calledFromTaskProcess || taskCount != 1) && taskCount != 0 && taskCount - outdatedTaskCount >= 0) { return; // If outdated tasks exists, don't create a new one. } // This task wil run in three minutes. // The third parameter could be a content item that represents the context for the task, but we don't need it now. _taskManager.CreateTask(TaskType, _clock.UtcNow.AddMinutes(3), null); // BTW this helper method and many more libraries aiding Orchard development are contained in the Helpful Libraries module: // http://helpfullibraries.codeplex.com/ }
public ActionResult Detail(int idQuestionario, string from = null, string to = null, bool export = false) { DateTime fromDate, toDate; CultureInfo provider = CultureInfo.GetCultureInfo(_orchardServices.WorkContext.CurrentCulture); DateTime.TryParse(from, provider, DateTimeStyles.None, out fromDate); DateTime.TryParse(to, provider, DateTimeStyles.None, out toDate); var model = _questionnairesServices.GetStats(idQuestionario, (DateTime?)fromDate, (DateTime?)toDate); if (export == true) { ContentItem filters = _orchardServices.ContentManager.Create("QuestionnaireStatsExport"); filters.As <TitlePart>().Title = string.Format("id={0}&from={1:yyyyMMdd}&to={2:yyyyMMdd}", idQuestionario, fromDate, toDate); _orchardServices.ContentManager.Publish(filters); _taskManager.CreateTask(StasExportScheduledTaskHandler.TaskType, DateTime.UtcNow.AddSeconds(-1), filters); //_questionnairesServices.SaveQuestionnaireUsersAnswers(idQuestionario, fromDate, toDate); _notifier.Add(NotifyType.Information, T("Export started. Please check 'Show Exported Files' in a few minutes to get the result.")); } return(View((object)model)); }
public ContentSyncSettingsPartHandler(IRepository <ContentSyncSettingsRecord> repository, IScheduledTaskManager scheduledTaskManager, IClock clock) { _scheduledTaskManager = scheduledTaskManager; _clock = clock; T = NullLocalizer.Instance; Filters.Add(new ActivatingFilter <ContentSyncSettingsPart>("Site")); Filters.Add(StorageFilter.For(repository)); OnUpdated <ContentSyncSettingsPart>((ctx, part) => { //schedule the snapshot task _scheduledTaskManager.DeleteTasks(null, a => a.TaskType == Constants.TakeSnapshotTaskName); if (part.SnapshotFrequencyMinutes == 0) { return; } _scheduledTaskManager.CreateTask(Constants.TakeSnapshotTaskName, _clock.UtcNow, null); }); }
public FeedSyncProfilePartHandler( IJsonConverter jsonConverter, IScheduledTaskManager scheduledTaskManager, IClock clock) { OnActivated <FeedSyncProfilePart>((context, part) => { part.MappingsField.Loader(() => { return(string.IsNullOrEmpty(part.MappingsSerialized) ? new List <Mapping>() : jsonConverter.Deserialize <List <Mapping> >(part.MappingsSerialized)); }); }); OnRemoved <FeedSyncProfilePart>((context, part) => { scheduledTaskManager.DeleteTasks(part.ContentItem); }); OnPublished <FeedSyncProfilePart>((context, part) => { part.PublishedCount++; if (context.PreviousItemVersionRecord != null) { scheduledTaskManager.DeleteTasks(part.ContentItem); // Because of the ContentType-first editor, we want to create the task only after // the second successful saving. scheduledTaskManager .CreateTask( part.ContentItem.GetFeedSyncProfileUpdaterTaskName(), clock.UtcNow.AddMinutes(1), part.ContentItem); } }); }
public void Process(ScheduledTaskContext context) { try { if (context.Task.TaskType != taskType) { return; } // esegue l'invio delle push var state = _pushGatewayService.PublishedPushEvent(context.Task.ContentItem); //verifica se rischedulare l'invio var pushSettings = _orchardServices.WorkContext.CurrentSite.As <PushMobileSettingsPart>(); var runAgain = _communicationService.GetRunAgainNeeded(context.Task.ContentItem.Id, "push", state.Errors, state.CompletedIteration, pushSettings.MaxNumRetry); if (runAgain) { // rischedula il task // applica il valore di default (5) nel caso di setting non valorizzato var delay = pushSettings.DelayMinutesBeforeRetry == 0 ? 5 : pushSettings.DelayMinutesBeforeRetry; _taskManager.CreateTask(taskType, DateTime.UtcNow.AddMinutes(delay), context.Task.ContentItem); } } catch (Exception ex) { Logger.Error(ex, "Error in PushScheduledTaskHandler. ContentItem: {0}, ScheduledUtc: {1:yyyy-MM-dd HH.mm.ss} Please verify if it is necessary sending your push again.", context.Task.ContentItem, context.Task.ScheduledUtc); } }
public void TaskManagerShouldCreateTaskRecordsWithOrWithoutContentItem() { var hello = _contentManager.New("hello"); _contentManager.Create(hello); _scheduledTaskManager.CreateTask("Ignore", _clock.UtcNow.AddHours(1), null); _scheduledTaskManager.CreateTask("Ignore", _clock.UtcNow.AddHours(2), hello); _session.Flush(); _session.Clear(); var tasks = _repository.Fetch(x => x != null); Assert.That(tasks.Count(), Is.EqualTo(2)); Assert.That(tasks, Has.All.Property("TaskType").EqualTo("Ignore")); var noContentItemTask = tasks.Single(x => x.ContentItemVersionRecord == null); Assert.That(noContentItemTask.ScheduledUtc, Is.EqualTo(_clock.UtcNow.AddHours(1))); Assert.That(noContentItemTask.ContentItemVersionRecord, Is.Null); var hasContentItemTask = tasks.Single(x => x.ContentItemVersionRecord != null); Assert.That(hasContentItemTask.ContentItemVersionRecord.ContentItemRecord.Id, Is.EqualTo(hello.Id)); Assert.That(hasContentItemTask.ContentItemVersionRecord.Id, Is.EqualTo(hello.VersionRecord.Id)); }
public void Activated() { _scheduledTaskManager.CreateTask("DemoTask", _clock.UtcNow.AddMinutes(1), null); }