Ejemplo n.º 1
0
        /// <summary>
        /// Install all events for the given object type. This is typically used to install scheduler items while installing packages.
        /// </summary>
        private async Task InstallItemsAsync(Type type)
        {
            string eventType = type.FullName + ", " + type.Assembly.GetName().Name;

            using (SchedulerDataProvider dataProvider = new SchedulerDataProvider()) {
                IScheduling schedEvt;
                try {
                    schedEvt = (IScheduling)Activator.CreateInstance(type);
                } catch (Exception exc) {
                    throw new InternalError("The specified object does not support the required IScheduling interface.", exc);
                }
                try {
                    SchedulerItemBase[] items = schedEvt.GetItems();
                    foreach (var item in items)
                    {
                        SchedulerItemData evnt = new SchedulerItemData();
                        ObjectSupport.CopyData(item, evnt);
                        evnt.Event.Name = item.EventName;
                        evnt.Event.ImplementingAssembly = type.Assembly.GetName().Name;
                        evnt.Event.ImplementingType     = type.FullName;
                        await dataProvider.AddItemAsync(evnt);// we ignore whether the add fails - it's OK if it already exists
                    }
                } catch (Exception exc) {
                    throw new InternalError("InstallEvents for the specified type {0} failed.", eventType, exc);
                }
            }
        }
Ejemplo n.º 2
0
        // SCHEDULER
        // SCHEDULER
        // SCHEDULER

        /// <summary>
        /// Run a scheduler item.
        /// </summary>
        /// <param name="name"></param>
        private async Task RunItemAsync(string name)
        {
            using (SchedulerDataProvider schedDP = new SchedulerDataProvider()) {
                using (ILockObject lockObject = await YetaWF.Core.IO.Caching.LockProvider.LockResourceAsync($"{AreaRegistration.CurrentPackage.AreaName}_RunItem_{name}")) {
                    SchedulerItemData evnt = await schedDP.GetItemAsync(name);

                    if (evnt == null)
                    {
                        throw new Error(this.__ResStr("errItemNotFound", "Scheduler item '{0}' does not exist."), name);
                    }
                    if (evnt.RunOnce)
                    {
                        evnt.Enabled = true;
                    }
                    if (!evnt.Enabled)
                    {
                        throw new Error(this.__ResStr("errItemDisabled", "Scheduler item '{0}' is currently disabled and cannot be scheduled."), evnt.Name);
                    }
                    evnt.Next   = DateTime.UtcNow.AddSeconds(-1);
                    evnt.Errors = null;
                    UpdateStatusEnum status = await schedDP.UpdateItemAsync(evnt);

                    await lockObject.UnlockAsync();

                    if (status != UpdateStatusEnum.OK)
                    {
                        throw new Error(this.__ResStr("errItemUpdFail", "Scheduler item '{0}' couldn't be updated."), evnt.Name);
                    }

                    Dispatch();// run the scheduler now
                }
            }
        }
Ejemplo n.º 3
0
            public SchedulerItemData GetEvent()
            {
                SchedulerItemData evnt = new SchedulerItemData();

                ObjectSupport.CopyData(this, evnt);
                return(evnt);
            }
Ejemplo n.º 4
0
        public async Task <ActionResult> SchedulerDisplay(string eventName)
        {
            using (SchedulerDataProvider dataProvider = new SchedulerDataProvider()) {
                SchedulerDisplayModel model = new SchedulerDisplayModel {
                };
                SchedulerItemData evnt      = await dataProvider.GetItemAsync(eventName);

                if (evnt == null)
                {
                    throw new Error(this.__ResStr("notFound", "Scheduler item \"{0}\" not found."), eventName);
                }
                model.SetEvent(evnt);
                Module.Title = this.__ResStr("modTitle", "Scheduler Item \"{0}\"", eventName);
                return(View(model));
            }
        }
Ejemplo n.º 5
0
        private async Task RunItemAsync(SchedulerDataProvider schedDP, SchedulerItemData item)
        {
            long logId = DateTime.UtcNow.Ticks;

            SchedulerLog.SetCurrent(logId, 0, item.Name);

            item.IsRunning = true;
            item.RunTime   = new TimeSpan();
            item.Last      = DateTime.UtcNow;

            try {
                await schedDP.UpdateItemAsync(item);
            } catch (Exception exc) {
                Logging.AddErrorLog("Updating scheduler item {0} failed.", item.Name, exc);
            }

            StringBuilder errors  = new StringBuilder();
            DateTime?     nextRun = null;// called event handlers can return a next run time

            try {
                item.Errors = null;

                DateTime now = DateTime.UtcNow;
                {
                    string m = $"Scheduler event - running scheduler item '{item.Name}'.";
                    Logging.AddLog(m);
                    errors.AppendLine(m);
                }

                Type tp = null;
                try {
                    Assembly asm = Assemblies.Load(item.Event.ImplementingAssembly);
                    tp = asm.GetType(item.Event.ImplementingType);
                } catch (Exception exc) {
                    throw new InternalError("Scheduler item '{0}' could not be loaded (Type={1}, Assembly={2}) - {3}", item.Name, item.Event.ImplementingType, item.Event.ImplementingAssembly, ErrorHandling.FormatExceptionMessage(exc));
                }

                if (item.SiteSpecific)
                {
                    DataProviderGetRecords <SiteDefinition> info = await SiteDefinition.GetSitesAsync(0, 0, null, null);

                    foreach (SiteDefinition site in info.Data)
                    {
                        IScheduling schedEvt = null;
                        try {
                            schedEvt = (IScheduling)Activator.CreateInstance(tp);
                        } catch (Exception exc) {
                            string m = $"Scheduler item '{item.Name}' could not be instantiated (Type={item.Event.ImplementingType}, Assembly={item.Event.ImplementingAssembly}) - {ErrorHandling.FormatExceptionMessage(exc)}";
                            Logging.AddLog(m);
                            errors.AppendLine(m);
                        }

                        if (schedEvt != null)
                        {
                            YetaWFManager.MakeThreadInstance(site, null, true);// set up a manager for the site

                            SchedulerLog.LimitTo(YetaWFManager.Manager);
                            SchedulerLog.SetCurrent(logId, site.Identity, item.Name);

                            SchedulerItemBase itemBase = new SchedulerItemBase {
                                Name = item.Name, Description = item.Description, EventName = item.Event.Name, Enabled = true, Frequency = item.Frequency, Startup = item.Startup, SiteSpecific = true
                            };
                            try {
                                await schedEvt.RunItemAsync(itemBase);
                            } catch (Exception exc) {
                                string m = $"An error occurred in scheduler item '{site.Identity}: {item.Name}' - {ErrorHandling.FormatExceptionMessage(exc)}";
                                Logging.AddLog(m);
                                errors.AppendLine(m);
                            }

                            foreach (var s in itemBase.Log)
                            {
                                string m = $"{site.Identity}: {s}";
                                Logging.AddLog(m);
                                errors.AppendLine(m);
                            }
                            if (itemBase.NextRun != null && (nextRun == null || (DateTime)itemBase.NextRun < nextRun))
                            {
                                nextRun = itemBase.NextRun;
                            }

                            YetaWFManager.RemoveThreadInstance();

                            YetaWFManager.MakeThreadInstance(null, null, true);// restore scheduler's manager
                            SchedulerLog.LimitTo(YetaWFManager.Manager);
                            SchedulerLog.SetCurrent();
                        }
                    }
                }
                else
                {
                    IScheduling schedEvt = null;
                    try {
                        schedEvt = (IScheduling)Activator.CreateInstance(tp);
                    } catch (Exception exc) {
                        string m = $"Scheduler item '{item.Name}' could not be instantiated (Type={item.Event.ImplementingType}, Assembly={item.Event.ImplementingAssembly}) - {ErrorHandling.FormatExceptionMessage(exc)}";
                        Logging.AddLog(m);
                        errors.AppendLine(m);
                    }

                    if (schedEvt != null)
                    {
                        SchedulerItemBase itemBase = new SchedulerItemBase {
                            Name = item.Name, Description = item.Description, EventName = item.Event.Name, Enabled = true, Frequency = item.Frequency, Startup = item.Startup, SiteSpecific = false
                        };
                        try {
                            await schedEvt.RunItemAsync(itemBase);
                        } catch (Exception exc) {
                            string m = $"An error occurred in scheduler item '{item.Name}' - {ErrorHandling.FormatExceptionMessage(exc)}";
                            Logging.AddLog(m);
                            errors.AppendLine(m);
                        }
                        foreach (var s in itemBase.Log)
                        {
                            Logging.AddLog(s);
                            errors.AppendLine(s);
                        }

                        if (itemBase.NextRun != null && (nextRun == null || (DateTime)itemBase.NextRun < nextRun))
                        {
                            nextRun = itemBase.NextRun;
                        }
                    }
                }

                TimeSpan diff = DateTime.UtcNow - now;
                item.RunTime = diff;
                {
                    string m = $"Elapsed time for scheduler item '{item.Name}' was {diff} (hh:mm:ss.ms).";
                    Logging.AddLog(m);
                    errors.AppendLine(m);
                }
            } catch (Exception exc) {
                string m = $"Scheduler item {item.Name} failed - {ErrorHandling.FormatExceptionMessage(exc)}";
                Logging.AddErrorLog(m);
                errors.AppendLine(m);
            }

            if (item.RunOnce)
            {
                item.Enabled = false;
            }

            item.IsRunning = false;

            item.SetNextRuntime();
            if (nextRun != null)
            {
                Logging.AddLog($"Next run at {nextRun} (UTC)");
                item.Next    = nextRun;
                item.Enabled = true;
            }
            item.Errors = errors.ToString();

            try {
                await schedDP.UpdateItemAsync(item);
            } catch (Exception exc) {
                string m = $"Updating scheduler item {item.Name} failed - {ErrorHandling.FormatExceptionMessage(exc)}";
                Logging.AddErrorLog(m);
                errors.AppendLine(m);
            }

            SchedulerLog.SetCurrent();
        }
Ejemplo n.º 6
0
        private async Task <TimeSpan> RunItemsAsync()
        {
            Logging.AddTraceLog("Scheduler event - checking scheduler items");

            using (SchedulerDataProvider schedDP = new SchedulerDataProvider()) {
                DateTime next = DateTime.UtcNow.Add(defaultTimeSpanNoTask);
                if (await schedDP.IsInstalledAsync())
                {
                    // run all items that are due now - Enabled == true and Next != null and Next < DateTime.UtcNow
                    List <DataProviderFilterInfo> filters = new List <DataProviderFilterInfo> {
                        new DataProviderFilterInfo {
                            Logic   = "&&",
                            Filters = new List <DataProviderFilterInfo> {
                                new DataProviderFilterInfo {
                                    Field = nameof(SchedulerItemData.Enabled), Operator = "==", Value = true,
                                },
                                new DataProviderFilterInfo {
                                    Field = nameof(SchedulerItemData.Next), Operator = "!=", Value = null,
                                },
                                new DataProviderFilterInfo {
                                    Field = nameof(SchedulerItemData.Next), Operator = "<=", Value = DateTime.UtcNow,
                                },
                            },
                        }
                    };
                    DataProviderGetRecords <SchedulerItemData> list = await schedDP.GetItemsAsync(filters);

                    foreach (SchedulerItemData item in list.Data)
                    {
                        await RunItemAsync(schedDP, item);
                    }

                    // Find the next startup time so we know how long to wait
                    List <DataProviderSortInfo> sorts = null;
                    sorts = DataProviderSortInfo.Join(sorts, new DataProviderSortInfo {
                        Field = nameof(SchedulerItemData.Next), Order = DataProviderSortInfo.SortDirection.Ascending
                    });
                    filters = new List <DataProviderFilterInfo> {
                        new DataProviderFilterInfo {
                            Logic   = "&&",
                            Filters = new List <DataProviderFilterInfo> {
                                new DataProviderFilterInfo {
                                    Field = nameof(SchedulerItemData.Enabled), Operator = "==", Value = true,
                                },
                                new DataProviderFilterInfo {
                                    Field = nameof(SchedulerItemData.Next), Operator = "!=", Value = null,
                                },
                            },
                        }
                    };
                    list = await schedDP.GetItemsAsync(0, 1, sorts, filters);

                    if (list.Data.Count > 0)
                    {
                        SchedulerItemData item = list.Data[0];
                        if (item.Next != null)
                        {
                            next = (DateTime)item.Next;
                        }
                    }
                }

                TimeSpan diff = next.Subtract(DateTime.UtcNow);
                if (diff < new TimeSpan(0, 0, 0))
                {
                    diff = new TimeSpan(0, 0, 1);
                }
                return(diff);
            }
        }
Ejemplo n.º 7
0
 public SchedulerItem(SchedulerBrowseModule module, SchedulerItemData evnt)
 {
     Module = module;
     ObjectSupport.CopyData(evnt, this);
 }
Ejemplo n.º 8
0
 public void SetEvent(SchedulerItemData evnt)
 {
     ObjectSupport.CopyData(evnt, this);
 }
Ejemplo n.º 9
0
 public void SetEvent(SchedulerItemData evnt)
 {
     ObjectSupport.CopyData(evnt, this);
     OriginalName = Name;
 }