示例#1
0
        private List <VirtualMachine> CreateDefaultVMs(List <string> vmNames)
        {
            var result = new List <VirtualMachine>();

            var disabledSchedule = new ScheduleConfig()
            {
                Type         = "SimpleSchedules.DailySchedule",
                OccursOnceAt = "00:00",
                Enabled      = false,
                Description  = "This schedule is disabled. Check Backup Task properties and after that enable this schedule."
            };

            foreach (string name in vmNames)
            {
                var vm = new VirtualMachine()
                {
                    Name = name,
                    ExportPathTemplate      = "C:\\Backup\\{HV_HOST_FULL}\\{HV_GUEST_FULL}\\Daily_{YEAR}_{MONTH}_{DAY}_{HOUR}_{MINUTE}",
                    ExportRotateDays        = 2,
                    CreateArchive           = true,
                    ArchivePathTemplate     = "C:\\Backup\\{HV_HOST_FULL}\\{HV_GUEST_FULL}\\{HV_HOST_SHORT}_HV_VM_{HV_GUEST_FULL}_export_{YEAR}.{MONTH}.{DAY}.{HOUR}.{MINUTE}.zip",
                    ArchiveCompressionLevel = 1,
                    ArchiveRotateDays       = 5,
                    SchedulesConfigs        = new List <ScheduleConfig>()
                    {
                        disabledSchedule
                    }
                };

                result.Add(vm);
            }

            return(result);
        }
        public static IServiceCollection AddBackgroundService <T>(this IServiceCollection services, Action <IScheduleConfig <T> > options) where T : AbstractBackgroundService
        {
            if (options == null)
            {
                throw new ArgumentNullException(Resource.ERROR_CONFIGURATION_NULL);
            }

            var config = new ScheduleConfig <T>();

            options.Invoke(config);

            if (string.IsNullOrWhiteSpace(config.CronExpression))
            {
                throw new ArgumentNullException(Resource.ERROR_CRON_NULL_EMPTY);
            }

            try
            {
                CronExpression.Parse(config.CronExpression);
            }
            catch
            {
                throw new InvalidCastException(Resource.ERROR_CRON_INVALID);
            }

            services.AddSingleton <IScheduleConfig <T> >(config);
            services.AddHostedService <T>();
            return(services);
        }
        public AppointmentSchedulerViewModel()
        {
            SiConfig = ScheduleConfig.GetInstance();
            lks      = new LKSEntities();

            GetCategories();

            addAppointmentCommand        = new BaseCommand(AddAppointment);
            editAppointmentCommand       = new BaseCommand(EditAppointment);
            setCurrentDayCommand         = new BaseCommand(SetCurrentDay);
            monthViewCommand             = new BaseCommand(GetMonthView);
            nextDayCommand               = new BaseCommand(NextDay);
            previousDayCommand           = new BaseCommand(PreviousDay);
            saveEditedAppointmentCommand = new BaseCommand(SaveAppointment);
            deleteAppointmentCommand     = new BaseCommand(DeleteAppointment);
            exitEditCommand              = new BaseCommand(ExitEdit);
            executeDeleteCommand         = new BaseCommand(ExecuteDelete);
            canceldeleteCommand          = new BaseCommand(CancelDelete);

            nextMonthCommand     = new BaseCommand(GetNextMonth);
            previousMonthCommand = new BaseCommand(getPrevMonth);

            SiConfig.DayNames = new ObservableCollection <string>()
            {
                "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
            };

            GetDays();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="operationName"></param>
        /// <param name="config"></param>
        /// <param name="arguments"></param>
        /// <param name="author"></param>
        /// <param name="documentationUrl"></param>
        /// <returns></returns>
        protected bool ScheduleOperation(string operationName, ScheduleConfig config,
                                         string arguments,
                                         string author           = "Footsteps Infotech Inc.",
                                         string documentationUrl = "http://www.footstepsinfotech.com")
        {
            bool success = false;

            try
            {
                using (TaskService service = new TaskService())
                {
                    try
                    {
                        // De-Register the task in the root folder  if it already exists
                        // service.RootFolder.DeleteTask(@"DBHealthCheck" + operationName.Replace(" ", ""));
                        Task task = service.GetTask(service.RootFolder.Path + @"DBHealthCheck" + operationName.Replace(" ", ""));
                        if (task != null)
                        {
                            service.RootFolder.DeleteTask(task.Name);
                        }
                    }
                    catch
                    {
                        // ignore
                    }

                    TaskDefinition definition = service.NewTask();

                    definition.RegistrationInfo.Description   = "DB Health Check " + operationName + " Scheduler Service";
                    definition.RegistrationInfo.Author        = author;
                    definition.RegistrationInfo.Date          = DateTime.Today;
                    definition.RegistrationInfo.Documentation = documentationUrl;
                    definition.Principal.RunLevel             = TaskRunLevel.Highest;
                    definition.Principal.LogonType            = TaskLogonType.ServiceAccount;

                    Trigger trigger = GetTrigger(operationName, config);

                    // Trigger must then be added to the task's trigger collection
                    definition.Triggers.Add(trigger);

                    // Create an action that will launch Notepad whenever the trigger fires
                    string path = Path.GetDirectoryName(Application.ExecutablePath);
                    // string path = @"D:\Subodh\Views\Websites\DBMaintenance\DBHealthCheckExecAction\bin\Debug";
                    definition.Actions.Add(new ExecAction(Path.Combine(path, @"DBHealthCheckExecAction.exe"),
                                                          arguments, path));

                    // Register the task in the root folder
                    service.RootFolder.RegisterTaskDefinition(@"DBHealthCheck" + operationName.Replace(" ", ""), definition,
                                                              TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                }
                success = true;
            }
            catch (Exception e)
            {
                LogUtil.Log(e.Message + Environment.NewLine + e.StackTrace);
                success = false;
            }
            return(success);
        }
示例#5
0
        public IActionResult AddEvent([FromBody] dynamic evt)
        {
            var  cycle    = 0;
            var  events   = new Dictionary <long, dynamic>();
            long parentId = 0;

            for (int i = 0; i < (int)evt.Cycle; i++)
            {
                DateTime date = evt.Start;
                for (int y = 0; y < cycle; y++)
                {
                    date = date.AddDays(7);
                }
                if (i == 0)
                {
                    var parentScheduleConfig = new ScheduleConfig
                    {
                        CommunityId = evt.CommunityId,
                        Date        = date,
                        Active      = true,
                        CreateBy    = 2,
                        CreateTime  = DateTime.UtcNow,
                        UpdateBy    = 2,
                        UpdateTime  = DateTime.UtcNow
                    };
                    _ctx.ScheduleConfig.Add(parentScheduleConfig);
                    _ctx.SaveChanges();
                    parentId = parentScheduleConfig.Id;
                    var community = _ctx.Community.FirstOrDefault(x => x.Id == parentScheduleConfig.CommunityId);
                    events.Add(parentScheduleConfig.Id, new { parentScheduleConfig.Date, community });
                }
                else
                {
                    var scheduleConfig = new ScheduleConfig
                    {
                        ParentId    = parentId,
                        CommunityId = evt.CommunityId,
                        Date        = date,
                        Active      = true,
                        CreateBy    = 2,
                        CreateTime  = DateTime.UtcNow,
                        UpdateBy    = 2,
                        UpdateTime  = DateTime.UtcNow
                    };
                    _ctx.ScheduleConfig.Add(scheduleConfig);
                    _ctx.SaveChanges();
                    var community = _ctx.Community.FirstOrDefault(x => x.Id == scheduleConfig.CommunityId);
                    events.Add(scheduleConfig.Id, new { scheduleConfig.Date, community });
                }
                cycle += 1;
            }

            var message = "";

            return(Json(new { message, events }));
        }
        public ShowScrapperScheduledService(ILogger <ShowScrapperScheduledService> logger, IClock clock,
                                            IOptions <ScheduleConfig> config, IServiceScopeFactory serviceScopeFactory) : base(logger)
        {
            _scheduleConfig      = config.Value;
            _clock               = clock;
            _serviceScopeFactory = serviceScopeFactory;

            _schedule = CrontabSchedule.Parse(_scheduleConfig.CronExpression);
            _nextRun  = _clock.GetCurrentInstant().ToDateTimeUtc();
        }
示例#7
0
    public static IServiceCollection AddCronJob <T>(this IServiceCollection services, Action <IScheduleConfig <T> > options) where T : CronJobService
    {
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options), @"Please provide Schedule Configurations.");
        }
        var config = new ScheduleConfig <T>();

        options.Invoke(config);
        if (string.IsNullOrWhiteSpace(config.CronExpression))
        {
            throw new ArgumentNullException(nameof(ScheduleConfig <T> .CronExpression), @"Empty Cron Expression is not allowed.");
        }
        services.AddSingleton <IScheduleConfig <T> >(config);
        services.AddHostedService <T>();
        return(services);
    }
        public static IServiceCollection AddCronJob <T>(this IServiceCollection services, Action <IScheduleConfig <T> > options) where T : CronJobService
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options), @"Configurações do serviço agendado estão ausentes.");
            }

            var config = new ScheduleConfig <T>();

            options.Invoke(config);
            if (string.IsNullOrWhiteSpace(config.CronExpression))
            {
                throw new ArgumentNullException(nameof(ScheduleConfig <T> .CronExpression), @"Expressão Cron não permitida.");
            }

            services.AddSingleton <IScheduleConfig <T> >(config);
            services.AddHostedService <T>();

            return(services);
        }
        public Task SetConfig(ScheduleConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var properties = config.GetChangedProperties();

            if (properties.Count == 0)
            {
                throw new ArgumentException("No config was set to be changed.", nameof(config));
            }

            properties["api"]     = "SYNO.DownloadStation.Schedule";
            properties["version"] = 1;
            properties["method"]  = "setconfig";
            properties["_sid"]    = _authInfo.SessionId;

            return(_client.GetAsync(@"DownloadStation/schedule.cgi", properties));
        }
    /// <summary>
    /// Adds scheduled cron job to application.
    /// </summary>
    /// <typeparam name="TJob"></typeparam>
    /// <param name="services"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static IServiceCollection AddMilvaCronJob <TJob>(this IServiceCollection services, Action <IScheduleConfig <TJob> > options) where TJob : MilvaCronJobService
    {
        if (options == null)
        {
            throw new MilvaDeveloperException("Please provide Schedule Configurations.");
        }

        var config = new ScheduleConfig <TJob>();

        options.Invoke(config);

        if (string.IsNullOrWhiteSpace(config.CronExpression))
        {
            throw new MilvaDeveloperException("Empty Cron Expression is not allowed.");
        }

        services.AddSingleton <IScheduleConfig <TJob> >(config);

        services.AddHostedService <TJob>();

        return(services);
    }
        /// <summary>
        /// Save te configurations for the passed Config
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        protected bool SaveConfigurations(ScheduleConfig config)
        {
            StringBuilder builder = new StringBuilder();
            IDictionary <string, string> values = ValidateInput(ref builder);

            if (!String.IsNullOrEmpty(builder.ToString()))
            {
                if (builder.ToString().IndexOf("ERR:", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    MessageBox.Show(builder.ToString(), "Validation Errors",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return(false);
                }
                else
                {
                    MessageBox.Show(builder.ToString(), "Validation Warnings",
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                    return(false);
                }
            }

            config.SaveConfigurations(values);
            return(true);
        }
示例#12
0
        public List <ScheduleConfig> GetScheduleCongfigs(string listSchedule)
        {
            List <ScheduleConfig> lstConfigs = new List <ScheduleConfig>();
            DataTable             dt         = dal.GetScheduleFileConfig(listSchedule);

            if (dt.Rows.Count < 0)
            {
                return(null);
            }

            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    ScheduleConfig config = new ScheduleConfig();
                    config.IntervalDefinition = row["intervalDef"].ToString();
                    config.ScheduleId         = Convert.ToInt32(row["scheduleId"]);
                    config.DayCode            = Convert.ToInt32(row["dayCode"]);
                    config.Interval           = Convert.ToInt32(row["interval"]);
                    config.H1 = Convert.ToInt32(row["H1"]);
                    config.M1 = Convert.ToInt32(row["M1"]);
                    config.S1 = Convert.ToInt32(row["S1"]);
                    config.H2 = Convert.ToInt32(row["H2"]);
                    config.M2 = Convert.ToInt32(row["M2"]);
                    config.S2 = Convert.ToInt32(row["S2"]);

                    lstConfigs.Add(config);
                }

                return(lstConfigs);
            }
            catch
            {
                return(null);
            }
        }
示例#13
0
        private void SetupScheduledJobs()
        {
            Log.LogInformation("Setting up scheduled jobs...");

            // Disabling AssetStatusJob until we are using 'dot on the map'. Until then it's redundant.
            //ServiceProvider.GetRequiredService<IDefaultJobRunner>()
            //               .StartDefaultJob(new RecurringJobRequest
            //               {
            //                 JobUid = AssetStatusJob.VSSJOB_UID,
            //                 Schedule = "* * * * *"
            //               });

            var config    = Configuration.GetValueString("MACHINE_EXPORT", "");
            var schConfig = new ScheduleConfig();

            if (!string.IsNullOrEmpty(config))
            {
                try
                {
                    schConfig = JsonConvert.DeserializeObject <ScheduleConfig>(config);
                }
                catch (Exception ex)
                {
                    Log.LogError(ex, "Configuration for MachinePasses is invalid");
                }

                ServiceProvider.GetRequiredService <IDefaultJobRunner>()
                .StartDefaultJob(new RecurringJobRequest
                {
                    JobUid          = Guid.Parse("39d6c48a-cc74-42d3-a839-1a6b77e8e076"),
                    Schedule        = schConfig.Schedule,
                    SetupParameters = schConfig.CustomerUid,
                    RunParameters   = schConfig.Emails
                });
            }
        }
示例#14
0
        public IActionResult UpdateEvent([FromBody] dynamic evt)
        {
            DateTime       InitialDate = evt.Start;
            long           eventId     = (long)evt.EventId;
            TimeSpan       dateDifference;
            var            events         = new Dictionary <long, DateTime>();
            var            eventSchedule  = _ctx.ScheduleConfig.First(x => x.Id == eventId);
            ScheduleConfig parentSchedule = _ctx.ScheduleConfig.FirstOrDefault(x => x.Id == eventSchedule.ParentId);

            if (parentSchedule != null)
            {
                dateDifference = parentSchedule.Date.Subtract(eventSchedule.Date);
                eventSchedule  = parentSchedule;
                InitialDate    = InitialDate.Add(dateDifference);
            }
            long parentId  = eventSchedule.ParentId ?? eventSchedule.Id;
            var  schedules = _ctx.ScheduleConfig.Where(x => x.ParentId == parentId || x.Id == parentId).ToList();
            var  cycle     = 0;

            foreach (var schedule in schedules)
            {
                schedule.Active = false;
                _ctx.SaveChanges();
            }
            for (int i = 0; i < (int)evt.Cycle; i++)
            {
                DateTime oldDate = eventSchedule.Date;
                DateTime newDate = InitialDate;
                for (int y = 0; y < cycle; y++)
                {
                    oldDate = oldDate.AddDays(7);
                    newDate = newDate.AddDays(7);
                }
                ScheduleConfig scheduledDate = schedules.Where(x => x.Date == oldDate).FirstOrDefault(x => x.CommunityId == eventSchedule.CommunityId);
                if (scheduledDate != null)
                {
                    scheduledDate.ParentId    = parentId;
                    scheduledDate.CommunityId = evt.CommunityId;
                    scheduledDate.Date        = newDate;
                    scheduledDate.Active      = true;
                    scheduledDate.UpdateBy    = 2;
                    scheduledDate.UpdateTime  = DateTime.UtcNow;
                    events.Add(scheduledDate.Id, scheduledDate.Date);
                    _ctx.SaveChanges();
                }
                else
                {
                    var scheduleConfig = new ScheduleConfig
                    {
                        ParentId    = parentId,
                        CommunityId = evt.CommunityId,
                        Date        = newDate,
                        Active      = true,
                        CreateBy    = 2,
                        CreateTime  = DateTime.UtcNow,
                        UpdateBy    = 2,
                        UpdateTime  = DateTime.UtcNow
                    };
                    _ctx.ScheduleConfig.Add(scheduleConfig);
                    _ctx.SaveChanges();
                    events.Add(scheduleConfig.Id, scheduleConfig.Date);
                }
                cycle += 1;
            }

            var message = "";

            return(Json(new { message, events }));
        }
示例#15
0
        private void Process(string[] args)
        {
            try
            {
                ScheduleConfig config = GetConfigFromFileName(args);

                string logFileName = config.GetCommandOperation();
                logFileName  = logFileName.Replace("[", "");
                logFileName  = logFileName.Replace("]", "");
                logFileName += "_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".log";

                LogFilePath = logFileName;

                StringBuilder commandPrintOutput = new StringBuilder();

                if (config is IndexConfig)
                {
                    // get the before screenshot
                    Log("*****************************************************");
                    Log("Before Snapshot for the fragmenation levels");
                    Log("*****************************************************");
                    LogDBFragLevel(config as IndexConfig);
                }

                DatabaseManager manager = new DatabaseManager();
                manager.ExecuteQuery(config.GetCommandOperation(),
                                     QueryMode.Update,
                                     config.GetCommandParameters(),
                                     commandPrintOutput,
                                     config.QueryExecutionTimeout);

                Log("Execution Completed Successfully...");

                if (!String.IsNullOrEmpty(commandPrintOutput.ToString()))
                {
                    Log("*************************************************************");
                    Log(config.GetCommandOperation() + " started @ " + DateTime.Now.ToShortDateString()
                        + " " + DateTime.Now.ToShortTimeString());
                    Log("*************************************************************");
                    Log(commandPrintOutput.ToString());

                    Log("*************************************************************");
                    Log("Execution successful @ " + DateTime.Now.ToShortDateString()
                        + " " + DateTime.Now.ToShortTimeString());
                    Log("*************************************************************");
                }

                if (config is IndexConfig)
                {
                    // get the post screenshot
                    Log("*****************************************************");
                    Log("After Snapshot for the fragmenation levels");
                    Log("*****************************************************");
                    LogDBFragLevel(config as IndexConfig);
                }

                // Mail Reports
                SystemConfig systemConfig = SystemConfig.GetInstance();

                if (systemConfig.CompressBackup && config is DoBackupConfig)
                {
                    // compression logic here
                    string compressedPath = Utility.CompressLastBackup();
                    Log("Backup File Successfully Compressed @ " + compressedPath);
                    compressedPath = null;
                }

                if (systemConfig.MailAlerts)
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append("<p>Hi,</p>");
                    builder.Append("<p>Scheduled [IndexOptimize] on database completed Successfully @ ");
                    builder.Append(DateTime.Now.ToString());
                    builder.Append("<br />The complete log of execution is attached. For any issues concerns please write");
                    builder.Append(" to us @ <a href=\"mailTo:[email protected]\" title=\"Write to Us\">");
                    builder.Append("[email protected]</a> or visit ");
                    builder.Append("<a href=\"http://www.footstepsinfotech.com/\" title=\"Footsteps Infotech Inc.\">");
                    builder.Append("www.footstepsinfotech.com</a></p><p>");
                    builder.Append("You can check the full execution log @ IndexOptimize_05052015020336.log</p>");
                    builder.Append("~<br />Thanks,<br />DB Health Check<br />© Footsteps Infotech Inc.");
                    MailUtility mailUtils = new MailUtility(systemConfig);
                    mailUtils.SendMail(builder.ToString(), "DB Health Check : "
                                       + config.GetCommandOperation() + " execution completed successfully", LogFilePath, false);

                    builder.Clear();
                    builder   = null;
                    mailUtils = null;
                }
            }
            catch (Exception e)
            {
                if (args.Length < 2)
                {
                    Log("Please pass the configuration name for execution");
                    Log("Execute the program as Program -c <configName>");
                    throw new ArgumentException("Please pass the configuration name for execution");
                }
                Log("Program invoked successfully... " + args);
                Log(e);
            }
        }
示例#16
0
        private void readCrontab()
        {
            ScheduleConfig _config = GerenciadorConfig.ReceberConfig <ScheduleConfig>();

            try
            {
                foreach (ScheduleItem item in _config.ScheduleItem)
                {
                    _cronlines.Add(item.value.Trim());
                    logger.Debug("Adding ScheduleItem [" + item.value.Trim() + "]");
                }
                String line;

                foreach (string linha in _cronlines)
                {
                    ArrayList minutes, hours, mDays, months, wDays;

                    line = linha;

                    if (line.Length == 0 || line.StartsWith("#"))
                    {
                        continue;
                    }

                    // re-escape space- and backslash-escapes in a cheap fashion
                    line = line.Replace("\\\\", "<BACKSLASH>");
                    line = line.Replace("\\ ", "<SPACE>");

                    // split string on whitespace
                    String[] cols = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                    for (int i = 0; i < cols.Length; i++)
                    {
                        cols[i] = cols[i].Replace("<BACKSLASH>", "\\");
                        cols[i] = cols[i].Replace("<SPACE>", " ");
                    }

                    if (cols.Length < 6)
                    {
                        reportError("Parse error in crontab (line too short).");
                        crontab = new ArrayList();
                    }

                    minutes = parseTimes(cols[0], 0, 59);
                    hours   = parseTimes(cols[1], 0, 23);
                    months  = parseTimes(cols[3], 1, 12);

                    if (!cols[2].Equals("*") && cols[3].Equals("*"))
                    {
                        // every n monthdays, disregarding weekdays
                        mDays = parseTimes(cols[2], 1, 31);
                        wDays = new ArrayList();
                        wDays.Add(-1);                          // empty value
                    }
                    else if (cols[2].Equals("*") && !cols[3].Equals("*"))
                    {
                        // every n weekdays, disregarding monthdays
                        mDays = new ArrayList();
                        mDays.Add(-1);                          // empty value
                        wDays = parseTimes(cols[4], 1, 7);      // 60 * 24 * 7
                    }
                    else
                    {
                        // every n weekdays, every m monthdays
                        mDays = parseTimes(cols[2], 1, 31);
                        wDays = parseTimes(cols[4], 1, 7);                          // 60 * 24 * 7
                    }

                    String args = "";

                    for (int i = 6; i < cols.Length; i++)
                    {
                        args += cols[i].Trim() + " ";
                    }

                    args = args.Trim();


                    // Prestar atencao aqui....inicializa com 6
                    ArrayList entry = new ArrayList(6);

                    entry.Add(months);
                    entry.Add(mDays);
                    entry.Add(wDays);
                    entry.Add(hours);
                    entry.Add(minutes);
                    entry.Add(cols[5]);
                    entry.Add(args);

                    crontab.Add(entry);

                    logger.Info("Command [" + cols[5] + "] scheduled to run");
                }
            }
            catch (Exception e)
            {
                reportError(e.ToString());
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="operationName"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        private Trigger GetTrigger(string operationName, ScheduleConfig config)
        {
            Trigger       trigger = null;
            string        temp    = null;
            string        time    = null;
            DaysOfTheWeek daysOfWeek;

            switch (config.RunInterval)
            {
            case RunInterval.Hourly:
                trigger = new TimeTrigger();
                // Set the time in between each repetition of the task after it starts to 30 minutes.
                trigger.Repetition.Interval = TimeSpan.FromMinutes(60);

                time = DateTime.Now.Hour + ":" + config.AdditionalInfo;
                // Set the start time for today as we want to start it immediately.
                trigger.StartBoundary = Convert.ToDateTime(DateTime.Today.ToShortDateString() + " " + time);
                break;

            case RunInterval.Daily:
                trigger = new DailyTrigger {
                    DaysInterval = 1
                };

                // Set the time the task will repeat to 1 day.
                time = config.AdditionalInfo + ":00";
                // Set the start time for today as we want to start it immediately.
                trigger.StartBoundary = Convert.ToDateTime(DateTime.Today.ToShortDateString() + " " + time);
                break;

            case RunInterval.Weekly:
                // Sunday at 02:00
                temp       = config.AdditionalInfo.Substring(0, config.AdditionalInfo.IndexOf("at"));
                temp       = temp.Trim();
                daysOfWeek = (DaysOfTheWeek)Enum.Parse(typeof(DaysOfTheWeek), temp);
                time       = config.AdditionalInfo.Substring(config.AdditionalInfo.IndexOf(temp + " at ") + (temp + " at ").Length);
                time       = time + ":00";
                trigger    = new WeeklyTrigger {
                    WeeksInterval = 1, DaysOfWeek = daysOfWeek, StartBoundary = Convert.ToDateTime(config.NextExecution)
                };
                break;

            case RunInterval.Fortnightly:
                // Sunday at 02:00
                temp       = config.AdditionalInfo.Substring(0, config.AdditionalInfo.IndexOf("at"));
                temp       = temp.Trim();
                daysOfWeek = (DaysOfTheWeek)Enum.Parse(typeof(DaysOfTheWeek), temp);
                time       = config.AdditionalInfo.Substring(config.AdditionalInfo.IndexOf(temp + " at ") + (temp + " at ").Length);
                time       = time + ":00";
                trigger    = new WeeklyTrigger {
                    WeeksInterval = 2, DaysOfWeek = daysOfWeek, StartBoundary = Convert.ToDateTime(config.NextExecution)
                };
                break;

            case RunInterval.Monthly:
                string day = config.AdditionalInfo.Substring(config.AdditionalInfo.IndexOf("On ") + "On ".Length,
                                                             config.AdditionalInfo.IndexOf(" @ ") - "On ".Length);
                trigger = new MonthlyTrigger {
                    DaysOfMonth  = new int[] { Convert.ToInt32(day) },
                    MonthsOfYear = MonthsOfTheYear.AllMonths
                };
                if (config.NextExecution == null)
                {
                    config.UpdateNextExecutionTime();
                }

                trigger.StartBoundary = DateTime.Now;
                break;

            case RunInterval.Yearly:
                trigger = new TimeTrigger();

                trigger.Repetition.Interval = TimeSpan.FromDays(365);

                // 28-Feb @ 02:01
                temp = config.AdditionalInfo.Substring(0, config.AdditionalInfo.IndexOf(" @ "));
                temp = temp.Trim();
                DateTime t = DateTime.ParseExact(config.AdditionalInfo, "dd-MMM", CultureInfo.InvariantCulture);

                trigger.StartBoundary = new DateTime(DateTime.Now.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second);
                break;
            }

            // Disable the trigger from firing the task
            trigger.Enabled = true; // Default is true

            // Set the task to end even if running when the duration is over
            // trigger.Repetition.StopAtDurationEnd = true; // Default is false

            // Set an identifier to be used when logging
            trigger.Id = "DBHeathCheck" + operationName.Replace(" ", "");

            // Set the maximum time this task can run once triggered to one hour.
            trigger.ExecutionTimeLimit = TimeSpan.FromHours(1);
            return(trigger);
        }