public void Execute(TaskExecutionContext ctx)
        {
			var storeUrl = _storeContext.CurrentStore.Url.TrimEnd('\\').EnsureEndsWith("/");
            string url = storeUrl + "keepalive/index";

            try
            {
                using (var wc = new WebClient())
                {
                    // FAKE a user-agent
					wc.Headers.Add("user-agent", @"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
                    if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) 
					{
						url = "http://" + url;
					}
					wc.DownloadString(url);
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
                    {
                        // the page was not found (as it can be expected with some webservers)
                        return;
                    }
                }
                // throw any other exception - this should not occur
                throw;
            }
        }
        public void Execute(TaskExecutionContext ctx)
        {
            var olderThan = DateTime.UtcNow.AddDays(-14);
            _qeRepository.DeleteAll(x => x.SentOnUtc.HasValue && x.CreatedOnUtc < olderThan);

            _qeRepository.Context.ShrinkDatabase();
        }
예제 #3
0
        public void Execute(TaskExecutionContext ctx)
        {
            const int pageSize = 1000;
            const int maxTries = 3;

            for (int i = 0; i < 9999999; ++i)
            {
                var q = new SearchEmailsQuery
                {
                    MaxSendTries = maxTries,
                    PageIndex = i,
                    PageSize = pageSize,
                    Expand = "Attachments",
                    UnsentOnly = true
                };
                var queuedEmails = _queuedEmailService.SearchEmails(q);

                foreach (var queuedEmail in queuedEmails)
                {
                    _queuedEmailService.SendEmail(queuedEmail);
                }

                if (!queuedEmails.HasNextPage)
                    break;
            }
        }
        /// <summary>
        /// Executes a task
        /// </summary>
		public void Execute(TaskExecutionContext ctx)
        {
            if (!_currencySettings.AutoUpdateEnabled)
                return;

            long lastUpdateTimeTicks = _currencySettings.LastUpdateTime;
            DateTime lastUpdateTime = DateTime.FromBinary(lastUpdateTimeTicks);
            lastUpdateTime = DateTime.SpecifyKind(lastUpdateTime, DateTimeKind.Utc);
            if (lastUpdateTime.AddHours(1) < DateTime.UtcNow)
            {
                //update rates each one hour
                var exchangeRates = _currencyService.GetCurrencyLiveRates(_currencyService.GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId).CurrencyCode);

                foreach (var exchageRate in exchangeRates)
                {
                    var currency = _currencyService.GetCurrencyByCode(exchageRate.CurrencyCode);
                    if (currency != null)
                    {
                        currency.Rate = exchageRate.Rate;
                        currency.UpdatedOnUtc = DateTime.UtcNow;
                        _currencyService.UpdateCurrency(currency);
                    }
                }

                //save new update time value
                _currencySettings.LastUpdateTime = DateTime.UtcNow.ToBinary();
                _settingService.SaveSetting(_currencySettings);
            }
        }
		public void Execute(TaskExecutionContext context)
		{
			var scope = context.LifetimeScope as ILifetimeScope;
			var googleService = scope.Resolve<IGoogleFeedService>();
			
			googleService.CreateFeed(context);
		}
예제 #6
0
        public void Execute(TaskExecutionContext ctx)
        {
            var storeUrl = _storeContext.CurrentStore.Url.TrimEnd('\\').EnsureEndsWith("/");
            string url = storeUrl + "keepalive/index";

            try
            {
                using (var wc = new WebClient())
                {
                    //wc.Headers.Add("SmartStore.NET"); // makes problems
                    if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                    {
                        url = "http://" + url;
                    }
                    wc.DownloadString(url);
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
                    {
                        // the page was not found (as it can be expected with some webservers)
                        return;
                    }
                }
                // throw any other exception - this should not occur
                throw;
            }
        }
        /// <summary>
        /// Executes a task
        /// </summary>
		public void Execute(TaskExecutionContext ctx)
        {
            var olderThanDays = 7; // TODO: move to settings
            var toUtc = DateTime.UtcNow.AddDays(-olderThanDays);

			_logger.ClearLog(toUtc, LogLevel.Error);
        }
        public void Execute(TaskExecutionContext ctx)
        {
            var profileId = ctx.ScheduleTask.Alias.ToInt();
            var profile = _importProfileService.GetImportProfileById(profileId);

            var request = new DataImportRequest(profile);

            request.ProgressValueSetter = delegate (int val, int max, string msg)
            {
                ctx.SetProgress(val, max, msg, true);
            };

            _importer.Import(request, ctx.CancellationToken);
        }
        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute(TaskExecutionContext ctx)
        {
            var maxTries = 3;
            var queuedEmails = _queuedEmailService.SearchEmails(null, null, null, null, true, maxTries, false, 0, 10000);

            foreach (var qe in queuedEmails)
            {
                var bcc = String.IsNullOrWhiteSpace(qe.Bcc)
                            ? null
                            : qe.Bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                var cc = String.IsNullOrWhiteSpace(qe.CC)
                            ? null
                            : qe.CC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                try
                {
                    var smtpContext = new SmtpContext(qe.EmailAccount);

                    var msg = new EmailMessage(
                        new EmailAddress(qe.To, qe.ToName),
                        qe.Subject,
                        qe.Body,
                        new EmailAddress(qe.From, qe.FromName));

                    if (qe.ReplyTo.HasValue())
                    {
                        msg.ReplyTo.Add(new EmailAddress(qe.ReplyTo, qe.ReplyToName));
                    }

                    if (cc != null)
                        msg.Cc.AddRange(cc.Where(x => x.HasValue()).Select(x => new EmailAddress(x)));

                    if (bcc != null)
                        msg.Bcc.AddRange(bcc.Where(x => x.HasValue()).Select(x => new EmailAddress(x)));

                    _emailSender.SendEmail(smtpContext, msg);

                    qe.SentOnUtc = DateTime.UtcNow;
                }
                catch (Exception exc)
                {
                    Logger.Error(string.Format("Error sending e-mail: {0}", exc.Message), exc);
                }
                finally
                {
                    qe.SentTries = qe.SentTries + 1;
                    _queuedEmailService.UpdateQueuedEmail(qe);
                }
            }
        }
		public void Execute(TaskExecutionContext ctx)
        {
			const int pageSize = 100;
			const int maxTries = 3;

			for (int i = 0; i < 9999999; ++i)
			{
				var queuedEmails = _queuedEmailService.SearchEmails(null, null, null, null, true, maxTries, false, i, pageSize, false);

				foreach (var queuedEmail in queuedEmails)
				{
					_queuedEmailService.SendEmail(queuedEmail);
				}

				if (!queuedEmails.HasNextPage)
					break;
			}
        }
예제 #11
0
        public void Execute(TaskExecutionContext ctx)
        {
            // delete all media records which are in transient state since at least 3 hours
            var olderThan = DateTime.UtcNow.AddHours(-3);

            // delete Downloads
            _downloadRepository.DeleteAll(x => x.IsTransient && x.UpdatedOnUtc < olderThan);

            // delete Pictures
            var autoCommit = _pictureRepository.AutoCommitEnabled;
            _pictureRepository.AutoCommitEnabled = false;

            try
            {
                using (var scope = new DbContextScope(autoDetectChanges: false, validateOnSave: false, hooksEnabled: false))
                {
                    var pictures = _pictureRepository.Where(x => x.IsTransient && x.UpdatedOnUtc < olderThan).ToList();
                    foreach (var picture in pictures)
                    {
                        _pictureService.DeletePicture(picture);
                    }

                    _pictureRepository.Context.SaveChanges();

                    if (DataSettings.Current.IsSqlServer)
                    {
                        try
                        {
                            _pictureRepository.Context.ExecuteSqlCommand("DBCC SHRINKDATABASE(0)", true);
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                _pictureRepository.AutoCommitEnabled = autoCommit;
            }
        }
예제 #12
0
        /// <summary>
        /// Executes the task
        /// </summary>
		/// <remarks>
		/// The caller is responsible for disposing the lifetime scope
		/// </remarks>
        public void Execute(
			CancellationToken cancellationToken,
			ILifetimeScope scope = null, 
			bool throwOnError = false)
        {
            this.IsRunning = true;
			var faulted = false;
			scope = scope ?? EngineContext.Current.ContainerManager.Scope();

			try
			{
				var task = this.CreateTask(scope);
				if (task != null)
				{
					this.LastStartUtc = DateTime.UtcNow;

					var scheduleTaskService = scope.Resolve<IScheduleTaskService>();
					var scheduleTask = scheduleTaskService.GetTaskByType(this.Type);

					if (scheduleTask != null)
					{
						//update appropriate datetime properties
						scheduleTask.LastStartUtc = this.LastStartUtc;
						scheduleTaskService.UpdateTask(scheduleTask);
					}

					//execute task
					var ctx = new TaskExecutionContext
					{
						LifetimeScope = scope,
						CancellationToken = cancellationToken
					};

					task.Execute(ctx);

					ctx.CancellationToken.ThrowIfCancellationRequested();
					this.LastEndUtc = this.LastSuccessUtc = DateTime.UtcNow;
					this.LastError = null;
				}
				else 
				{
					faulted = true;
					this.LastError = "Could not create task instance";
				}
			}
			catch (Exception ex)
			{
				faulted = true;
				this.Enabled = !this.StopOnError;
				this.LastEndUtc = DateTime.UtcNow;
				this.LastError = ex.Message.Truncate(995, "...");

				//log error
				var logger = scope.Resolve<ILogger>();
				logger.Error(string.Format("Error while running the '{0}' schedule task. {1}", this.Name, ex.Message), ex);
				if (throwOnError)
				{
					throw;
				}
			}
			finally
			{
				var scheduleTaskService = scope.Resolve<IScheduleTaskService>();
				var scheduleTask = scheduleTaskService.GetTaskByType(this.Type);

				if (scheduleTask != null)
				{
					// update appropriate properties
					scheduleTask.LastError = this.LastError;
					scheduleTask.LastEndUtc = this.LastEndUtc;
					if (!faulted)
					{
						scheduleTask.LastSuccessUtc = this.LastSuccessUtc;
					}

					scheduleTaskService.UpdateTask(scheduleTask);
				}

				this.IsRunning = false;
			}
        }
예제 #13
0
        public void Execute(ScheduleTask task, bool throwOnError = false)
        {
            if (task.IsRunning)
                return;

            if (AsyncRunner.AppShutdownCancellationToken.IsCancellationRequested)
                return;

            bool faulted = false;
            bool canceled = false;
            string lastError = null;
            ITask instance = null;
            string stateName = null;

            Type taskType = null;

            try
            {
                taskType = Type.GetType(task.Type);
                if (!PluginManager.IsActivePluginAssembly(taskType.Assembly))
                    return;
            }
            catch
            {
                return;
            }

            try
            {
                // set background task system customer as current customer
                var customer = _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);
                _workContext.CurrentCustomer = customer;

                // create task instance
                instance = _taskResolver(taskType);
                stateName = task.Id.ToString();

                // prepare and save entity
                task.LastStartUtc = DateTime.UtcNow;
                task.LastEndUtc = null;
                task.NextRunUtc = null;
                task.ProgressPercent = null;
                task.ProgressMessage = null;

                _scheduledTaskService.UpdateTask(task);

                // create & set a composite CancellationTokenSource which also contains the global app shoutdown token
                var cts = CancellationTokenSource.CreateLinkedTokenSource(AsyncRunner.AppShutdownCancellationToken, new CancellationTokenSource().Token);
                AsyncState.Current.SetCancelTokenSource<ScheduleTask>(cts, stateName);

                var ctx = new TaskExecutionContext(_componentContext, task)
                {
                    ScheduleTask = task.Clone(),
                    CancellationToken = cts.Token
                };

                instance.Execute(ctx);
            }
            catch (Exception ex)
            {
                faulted = true;
                canceled = ex is OperationCanceledException;
                Logger.Error(string.Format("Error while running scheduled task '{0}'. {1}", task.Name, ex.Message), ex);
                lastError = ex.Message.Truncate(995, "...");
                if (throwOnError)
                {
                    throw;
                }
            }
            finally
            {
                // remove from AsyncState
                if (stateName.HasValue())
                {
                    AsyncState.Current.Remove<ScheduleTask>(stateName);
                }

                task.ProgressPercent = null;
                task.ProgressMessage = null;

                var now = DateTime.UtcNow;
                task.LastError = lastError;
                task.LastEndUtc = now;

                if (faulted)
                {
                    if ((!canceled && task.StopOnError) || instance == null)
                    {
                        task.Enabled = false;
                    }
                }
                else
                {
                    task.LastSuccessUtc = now;
                }

                if (task.Enabled)
                {
                    task.NextRunUtc = _scheduledTaskService.GetNextSchedule(task);
                }

                _scheduledTaskService.UpdateTask(task);
            }
        }
예제 #14
0
 public void CreateFeed(TaskExecutionContext context)
 {
     Helper.StartCreatingFeeds(fileCreation =>
     {
         CreateFeed(fileCreation, context);
         return true;
     });
 }
예제 #15
0
        private void CreateFeed(FeedFileCreationContext fileCreation, TaskExecutionContext taskContext)
        {
            var xmlSettings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CheckCharacters = false
            };

            using (var writer = XmlWriter.Create(fileCreation.Stream, xmlSettings))
            {
                try
                {
                    fileCreation.Logger.Information("Log file - Google Merchant Center feed.");

                    var searchContext = new ProductSearchContext
                    {
                        OrderBy = ProductSortingEnum.CreatedOn,
                        PageSize = Settings.PageSize,
                        StoreId = fileCreation.Store.Id,
                        VisibleIndividuallyOnly = true
                    };

                    var currency = _currencyService.GetCurrencyById(Settings.CurrencyId);
                    var measureWeightSystemKey = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword;

                    if (currency == null || !currency.Published)
                        currency = _services.WorkContext.WorkingCurrency;

                    writer.WriteStartDocument();
                    writer.WriteStartElement("rss");
                    writer.WriteAttributeString("version", "2.0");
                    writer.WriteAttributeString("xmlns", "g", null, _googleNamespace);
                    writer.WriteStartElement("channel");
                    writer.WriteElementString("title", "{0} - Feed for Google Merchant Center".FormatWith(fileCreation.Store.Name));
                    writer.WriteElementString("link", "http://base.google.com/base/");
                    writer.WriteElementString("description", "Information about products");

                    for (int i = 0; i < 9999999; ++i)
                    {
                        searchContext.PageIndex = i;

                        // Perf
                        _dbContext.DetachAll();

                        var products = _productService.SearchProducts(searchContext);

                        if (fileCreation.TotalRecords == 0)
                            fileCreation.TotalRecords = products.TotalCount * fileCreation.StoreCount;	// approx

                        foreach (var product in products)
                        {
                            fileCreation.Report();

                            if (product.ProductType == ProductType.SimpleProduct || product.ProductType == ProductType.BundledProduct)
                            {
                                WriteItem(fileCreation, writer, product, currency, measureWeightSystemKey);
                            }
                            else if (product.ProductType == ProductType.GroupedProduct)
                            {
                                var associatedSearchContext = new ProductSearchContext
                                {
                                    OrderBy = ProductSortingEnum.CreatedOn,
                                    PageSize = int.MaxValue,
                                    StoreId = fileCreation.Store.Id,
                                    VisibleIndividuallyOnly = false,
                                    ParentGroupedProductId = product.Id
                                };

                                foreach (var associatedProduct in _productService.SearchProducts(associatedSearchContext))
                                {
                                    WriteItem(fileCreation, writer, associatedProduct, currency, measureWeightSystemKey);
                                }
                            }

                            if (taskContext.CancellationToken.IsCancellationRequested)
                            {
                                fileCreation.Logger.Warning("A cancellation has been requested");
                                break;
                            }
                        }

                        if (!products.HasNextPage || taskContext.CancellationToken.IsCancellationRequested)
                            break;
                    }

                    writer.WriteEndElement(); // channel
                    writer.WriteEndElement(); // rss
                    writer.WriteEndDocument();

                    if (fileCreation.ErrorMessage.HasValue())
                        fileCreation.Logger.Error(fileCreation.ErrorMessage);
                }
                catch (Exception exc)
                {
                    fileCreation.Logger.Error(exc.Message, exc);
                }
            }
        }
		/// <summary>
        /// Executes a task
        /// </summary>
		public void Execute(TaskExecutionContext ctx)
        {
			_cacheManager.Clear();
        }
예제 #17
0
        public void Execute(
            ScheduleTask task,
            IDictionary <string, string> taskParameters = null,
            bool throwOnError = false)
        {
            if (task.IsRunning)
            {
                return;
            }

            if (AsyncRunner.AppShutdownCancellationToken.IsCancellationRequested)
            {
                return;
            }

            bool   faulted   = false;
            bool   canceled  = false;
            string lastError = null;
            ITask  instance  = null;
            string stateName = null;

            Type taskType = null;

            try
            {
                taskType = Type.GetType(task.Type);

                Debug.WriteLineIf(taskType == null, "Invalid task type: " + task.Type.NaIfEmpty());

                if (taskType == null)
                {
                    return;
                }

                if (!PluginManager.IsActivePluginAssembly(taskType.Assembly))
                {
                    return;
                }
            }
            catch
            {
                return;
            }

            try
            {
                Customer customer = null;

                // try virtualize current customer (which is necessary when user manually executes a task)
                if (taskParameters != null && taskParameters.ContainsKey(CurrentCustomerIdParamName))
                {
                    customer = _customerService.GetCustomerById(taskParameters[CurrentCustomerIdParamName].ToInt());
                }

                if (customer == null)
                {
                    // no virtualization: set background task system customer as current customer
                    customer = _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);
                }

                _workContext.CurrentCustomer = customer;

                // create task instance
                instance  = _taskResolver(taskType);
                stateName = task.Id.ToString();

                // prepare and save entity
                task.LastStartUtc    = DateTime.UtcNow;
                task.LastEndUtc      = null;
                task.NextRunUtc      = null;
                task.ProgressPercent = null;
                task.ProgressMessage = null;

                _scheduledTaskService.UpdateTask(task);

                // create & set a composite CancellationTokenSource which also contains the global app shoutdown token
                var cts = CancellationTokenSource.CreateLinkedTokenSource(AsyncRunner.AppShutdownCancellationToken, new CancellationTokenSource().Token);
                AsyncState.Current.SetCancelTokenSource <ScheduleTask>(cts, stateName);

                var ctx = new TaskExecutionContext(_componentContext, task)
                {
                    ScheduleTask      = task.Clone(),
                    CancellationToken = cts.Token,
                    Parameters        = taskParameters ?? new Dictionary <string, string>()
                };

                instance.Execute(ctx);
            }
            catch (Exception exception)
            {
                faulted   = true;
                canceled  = exception is OperationCanceledException;
                lastError = exception.Message.Truncate(995, "...");

                if (canceled)
                {
                    Logger.Warning(T("Admin.System.ScheduleTasks.Cancellation", task.Name), exception);
                }
                else
                {
                    Logger.Error(string.Concat(T("Admin.System.ScheduleTasks.RunningError", task.Name), ": ", exception.Message), exception);
                }

                if (throwOnError)
                {
                    throw;
                }
            }
            finally
            {
                // remove from AsyncState
                if (stateName.HasValue())
                {
                    AsyncState.Current.Remove <ScheduleTask>(stateName);
                }

                task.ProgressPercent = null;
                task.ProgressMessage = null;

                var now = DateTime.UtcNow;
                task.LastError  = lastError;
                task.LastEndUtc = now;

                if (faulted)
                {
                    if ((!canceled && task.StopOnError) || instance == null)
                    {
                        task.Enabled = false;
                    }
                }
                else
                {
                    task.LastSuccessUtc = now;
                }

                if (task.Enabled)
                {
                    task.NextRunUtc = _scheduledTaskService.GetNextSchedule(task);
                }

                _scheduledTaskService.UpdateTask(task);
            }
        }
예제 #18
0
        public async Task ExecuteAsync(
            ScheduleTask entity,
            IDictionary <string, string> taskParameters = null,
            bool throwOnError = false)
        {
            if (AsyncRunner.AppShutdownCancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (entity.LastHistoryEntry == null)
            {
                // The task was started manually.
                entity.LastHistoryEntry = _scheduledTaskService.GetLastHistoryEntryByTaskId(entity.Id);
            }

            if (entity?.LastHistoryEntry?.IsRunning == true)
            {
                return;
            }

            bool      faulted   = false;
            bool      canceled  = false;
            string    lastError = null;
            ITask     task      = null;
            string    stateName = null;
            Type      taskType  = null;
            Exception exception = null;

            var historyEntry = new ScheduleTaskHistory
            {
                ScheduleTaskId = entity.Id,
                IsRunning      = true,
                MachineName    = _env.MachineName.EmptyNull(),
                StartedOnUtc   = DateTime.UtcNow
            };

            try
            {
                taskType = Type.GetType(entity.Type);
                if (taskType == null)
                {
                    Logger.DebugFormat("Invalid scheduled task type: {0}", entity.Type.NaIfEmpty());
                }

                if (taskType == null)
                {
                    return;
                }

                if (!PluginManager.IsActivePluginAssembly(taskType.Assembly))
                {
                    return;
                }

                entity.ScheduleTaskHistory.Add(historyEntry);
                _scheduledTaskService.UpdateTask(entity);
            }
            catch
            {
                return;
            }

            try
            {
                // Task history entry has been successfully added, now we execute the task.
                // Create task instance.
                task      = _taskResolver(taskType);
                stateName = entity.Id.ToString();

                // Create & set a composite CancellationTokenSource which also contains the global app shoutdown token.
                var cts = CancellationTokenSource.CreateLinkedTokenSource(AsyncRunner.AppShutdownCancellationToken, new CancellationTokenSource().Token);
                _asyncState.SetCancelTokenSource <ScheduleTask>(cts, stateName);

                var ctx = new TaskExecutionContext(_componentContext, historyEntry)
                {
                    ScheduleTaskHistory = historyEntry.Clone(),
                    CancellationToken   = cts.Token,
                    Parameters          = taskParameters ?? new Dictionary <string, string>()
                };

                Logger.DebugFormat("Executing scheduled task: {0}", entity.Type);

                if (task is IAsyncTask asyncTask)
                {
                    await asyncTask.ExecuteAsync(ctx);
                }
                else
                {
                    task.Execute(ctx);
                }
            }
            catch (Exception ex)
            {
                exception = ex;
                faulted   = true;
                canceled  = ex is OperationCanceledException;
                lastError = ex.ToAllMessages(true);

                if (canceled)
                {
                    Logger.Warn(ex, T("Admin.System.ScheduleTasks.Cancellation", entity.Name));
                }
                else
                {
                    Logger.Error(ex, string.Concat(T("Admin.System.ScheduleTasks.RunningError", entity.Name), ": ", ex.Message));
                }
            }
            finally
            {
                var now        = DateTime.UtcNow;
                var updateTask = false;

                historyEntry.IsRunning       = false;
                historyEntry.ProgressPercent = null;
                historyEntry.ProgressMessage = null;
                historyEntry.Error           = lastError;
                historyEntry.FinishedOnUtc   = now;

                if (faulted)
                {
                    if ((!canceled && entity.StopOnError) || task == null)
                    {
                        entity.Enabled = false;
                        updateTask     = true;
                    }
                }
                else
                {
                    historyEntry.SucceededOnUtc = now;
                }

                try
                {
                    Logger.DebugFormat("Executed scheduled task: {0}. Elapsed: {1} ms.", entity.Type, (now - historyEntry.StartedOnUtc).TotalMilliseconds);

                    // Remove from AsyncState.
                    if (stateName.HasValue())
                    {
                        // We don't just remove the cancellation token, but the whole state (along with the token)
                        // for the case that a state was registered during task execution.
                        _asyncState.Remove <ScheduleTask>(stateName);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }

                if (entity.Enabled)
                {
                    entity.NextRunUtc = _scheduledTaskService.GetNextSchedule(entity);
                    updateTask        = true;
                }

                _scheduledTaskService.UpdateHistoryEntry(historyEntry);

                if (updateTask)
                {
                    _scheduledTaskService.UpdateTask(entity);
                }

                Throttle.Check("Delete old schedule task history entries", TimeSpan.FromDays(1), () => _scheduledTaskService.DeleteHistoryEntries() > 0);
            }

            if (throwOnError && exception != null)
            {
                throw exception;
            }
        }
        private void CreateFeed(FeedFileCreationContext fileCreation, TaskExecutionContext taskContext)
        {
            var xmlSettings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CheckCharacters = false
            };

            using (var writer = XmlWriter.Create(fileCreation.Stream, xmlSettings))
            {
                try
                {
                    fileCreation.Logger.Information("Log file - Google Merchant Center feed.");

                    var searchContext = new ProductSearchContext()
                    {
                        OrderBy = ProductSortingEnum.CreatedOn,
                        PageSize = int.MaxValue,
                        StoreId = fileCreation.Store.Id,
                        VisibleIndividuallyOnly = true
                    };

                    string breakingError = null;
                    var qualifiedProducts = new List<Product>();
                    var currency = Helper.GetUsedCurrency(Settings.CurrencyId);
                    var products = _productService.SearchProducts(searchContext);
                    var measureWeightSystemKey = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword;

                    if (fileCreation.TotalRecords == 0)
                        fileCreation.TotalRecords = products.Count * fileCreation.StoreCount;

                    writer.WriteStartDocument();
                    writer.WriteStartElement("rss");
                    writer.WriteAttributeString("version", "2.0");
                    writer.WriteAttributeString("xmlns", "g", null, _googleNamespace);
                    writer.WriteStartElement("channel");
                    writer.WriteElementString("title", "{0} - Feed for Google Merchant Center".FormatWith(fileCreation.Store.Name));
                    writer.WriteElementString("link", "http://base.google.com/base/");
                    writer.WriteElementString("description", "Information about products");

                    foreach (var product in products)
                    {
                        fileCreation.Report();

                        Helper.GetQualifiedProductsByProduct(product, fileCreation.Store, qualifiedProducts);

                        foreach (var qualifiedProduct in qualifiedProducts)
                        {
                            writer.WriteStartElement("item");

                            try
                            {
                                breakingError = WriteItem(writer, fileCreation.Store, qualifiedProduct, currency, measureWeightSystemKey);
                            }
                            catch (Exception exc)
                            {
                                fileCreation.Logger.Error(exc.Message, exc);
                            }

                            writer.WriteEndElement(); // item
                        }

                        if (breakingError.HasValue())
                        {
                            fileCreation.Logger.Error(breakingError);
                            break;
                        }
                        if (taskContext.CancellationToken.IsCancellationRequested)
                        {
                            fileCreation.Logger.Warning("A cancellation has been requested");
                            break;
                        }
                    }

                    writer.WriteEndElement(); // channel
                    writer.WriteEndElement(); // rss
                    writer.WriteEndDocument();

                    if (breakingError.HasValue())
                        throw new SmartException(breakingError);
                }
                catch (Exception exc)
                {
                    fileCreation.Logger.Error(exc.Message, exc);
                }
            }
        }
		public void Execute(TaskExecutionContext ctx)
        {
			_apiService.DataPollingTaskProcess();
        }
        /// <summary>
        /// Executes a task
        /// </summary>
		public void Execute(TaskExecutionContext ctx)
        {
            //60*24 = 1 day
            var olderThanMinutes = 1440; // TODO: move to settings
            _customerService.DeleteGuestCustomers(null, DateTime.UtcNow.AddMinutes(-olderThanMinutes), true);
        }
예제 #22
0
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <remarks>
        /// The caller is responsible for disposing the lifetime scope
        /// </remarks>
        public void Execute(
            CancellationToken cancellationToken,
            ILifetimeScope scope = null,
            bool throwOnError    = false)
        {
            this.IsRunning = true;
            var faulted = false;

            scope = scope ?? EngineContext.Current.ContainerManager.Scope();

            try
            {
                var task = this.CreateTask(scope);
                if (task != null)
                {
                    this.LastStartUtc = DateTime.UtcNow;

                    var scheduleTaskService = scope.Resolve <IScheduleTaskService>();
                    var scheduleTask        = scheduleTaskService.GetTaskByType(this.Type);

                    if (scheduleTask != null)
                    {
                        //update appropriate datetime properties
                        scheduleTask.LastStartUtc = this.LastStartUtc;
                        scheduleTaskService.UpdateTask(scheduleTask);
                    }

                    //execute task
                    var ctx = new TaskExecutionContext
                    {
                        LifetimeScope     = scope,
                        CancellationToken = cancellationToken
                    };

                    task.Execute(ctx);

                    ctx.CancellationToken.ThrowIfCancellationRequested();
                    this.LastEndUtc = this.LastSuccessUtc = DateTime.UtcNow;
                    this.LastError  = null;
                }
                else
                {
                    faulted        = true;
                    this.LastError = "Could not create task instance";
                }
            }
            catch (Exception ex)
            {
                faulted         = true;
                this.Enabled    = !this.StopOnError;
                this.LastEndUtc = DateTime.UtcNow;
                this.LastError  = ex.Message.Truncate(995, "...");

                //log error
                var logger = scope.Resolve <ILogger>();
                logger.Error(string.Format("Error while running the '{0}' schedule task. {1}", this.Name, ex.Message), ex);
                if (throwOnError)
                {
                    throw;
                }
            }
            finally
            {
                var scheduleTaskService = scope.Resolve <IScheduleTaskService>();
                var scheduleTask        = scheduleTaskService.GetTaskByType(this.Type);

                if (scheduleTask != null)
                {
                    // update appropriate properties
                    scheduleTask.LastError  = this.LastError;
                    scheduleTask.LastEndUtc = this.LastEndUtc;
                    if (!faulted)
                    {
                        scheduleTask.LastSuccessUtc = this.LastSuccessUtc;
                    }

                    scheduleTaskService.UpdateTask(scheduleTask);
                }

                this.IsRunning = false;
            }
        }
 public void Execute(TaskExecutionContext context)
 {
     _feedService.CreateFeed(context);
     context.CancellationToken.ThrowIfCancellationRequested();
 }
		public void Execute(TaskExecutionContext ctx)
		{
			FileSystemHelper.TempCleanup();
		}