예제 #1
0
        /// <summary>Processes any jobs that have been added.</summary>
        /// <param name="jobManager">The job manager.</param>
        private void ProcessAddedJobs(JobManager jobManager)
        {
            JobsService.Job runningJobDescription = null;

            //If there is no YP job running, then add a new job.  Once a YP job is running don't add any more jobs (regardless of type).
            if (runningJob == null || jobManager.IsJobCompleted(runningJob))
            {
                // Remove completed jobs if nothing is running. Otherwise, completedjobs will
                // grow and grow.
                jobManager.ClearCompletedJobs();
                runningJob = null;

                using (JobsService.JobsClient jobsClient = new JobsService.JobsClient())
                {
                    runningJobDescription = jobsClient.GetNextToRun();
                }

                if (runningJobDescription != null)
                {
                    if (RunnableJobs.ProcessYPJob.IsF4PJob(runningJobDescription.Name) == true)
                        runningJob = new RunnableJobs.ProcessF4PJob(true) { JobName = runningJobDescription.Name };
                    else
                        runningJob = new RunnableJobs.ProcessYPJob(true) { JobName = runningJobDescription.Name };
                    if (runningJob != null)
                        jobManager.AddJob(runningJob);
                }
                else
                {
                    // No jobs to run so wait a bit.
                    Thread.Sleep(15 * 1000); // 15 sec.
                }
            }
        }
예제 #2
0
 protected override void OnStart(string[] args)
 {
     if (jobManager == null)
     {
         jobManager = new JobManager(maximumNumberOfProcessors);
         jobManager.AddJob(new RunJobsInDB());
     }
     jobManager.Start(waitUntilFinished: false);
 }
예제 #3
0
        /// <summary>Called when the form is loaded</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void OnLoad(object sender, EventArgs e)
        {
            int maximumNumberOfCores = -1;
            if (arguments.ContainsKey("-MaximumNumberOfCores"))
                maximumNumberOfCores = Convert.ToInt32(arguments["-MaximumNumberOfCores"]);

            jobManager = new JobManager(maximumNumberOfCores);
            jobManager.AddJob(new RunJobsInDB());
            jobManager.Start(waitUntilFinished: false);
        }
예제 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // FIXME: Add global RequireHttps attribute to all routes when not debugging
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            /* FIXME TEMP: CORS is set up to allow any origin in for now; need to configure to
             * restrict to specific front-ends */
            /* FIXME: When controller exceptions fall through, ASP.NET doesn't include the
             * Access-Control-Allow-Origin pair in the response header. */
            app.UseCors(cfg =>
            {
                cfg.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
            });
            app.UseAuthentication();
            app.UseMvc();

            JobManager.AddJob(
                new SessionTokenMaintenance(app.ApplicationServices.GetService <DbContextOptions>()),
                s => s.ToRunEvery(1).Days().At(0, 0) //Run every day at midnight
                );
        }
예제 #5
0
        public void Execute()
        {
            lock (_lock)
            {
                if (_options.IsDisabled || _shuttingDown)
                {
                    return;
                }

                var switchOffTime = _timeProvider.Today.Add(_options.SwitchOffTime);
                var sunsetSwitchSchedulingTime    = _timeProvider.Today.Add(_options.SunsetSwitchSchedulingTime);
                var switchOffTimeUtc              = switchOffTime.ConvertToUtc(_timeProvider.TimeZone);
                var sunsetSwitchSchedulingTimeUtc = sunsetSwitchSchedulingTime.ConvertToUtc(_timeProvider.TimeZone);

                _logger.LogInformation("Scheduling light switcher job at " +
                                       $"{sunsetSwitchSchedulingTime} ({sunsetSwitchSchedulingTimeUtc} UTC) and {switchOffTime} ({switchOffTimeUtc} UTC) " +
                                       $"for timezone {_timeProvider.TimeZone.DisplayName}");

                JobManager.AddJob <LightSwitcherJob>(
                    x => x.ToRunNow().AndEvery(1).Days().At(sunsetSwitchSchedulingTimeUtc.Hour, sunsetSwitchSchedulingTimeUtc.Minute));
                JobManager.AddJob <LightSwitcherJob>(
                    x => x.ToRunEvery(0).Days().At(switchOffTimeUtc.Hour, switchOffTimeUtc.Minute));
            }
        }
예제 #6
0
 /// <summary>Runs the job (.xml file) specified on the command line.</summary>
 /// <returns>True if something was run.</returns>
 private static bool RunJobFromCommandLine(string[] commandLineArguments)
 {
     if (commandLineArguments.Length > 0 && File.Exists(commandLineArguments[0]))
     {
         bool runAPSIM = !(commandLineArguments.Length == 2 &&
                           commandLineArguments[1] == "/DontRunAPSIM");
         RunnableJobs.ProcessYPJob job = new RunnableJobs.ProcessYPJob(runAPSIM);
         job.JobFileName = commandLineArguments[0];
         if (commandLineArguments.Length > 1)
             job.ApsimExecutable = commandLineArguments[1];
         JobManager jobManager = new JobManager();
         jobManager.AddJob(job);
         jobManager.Start(waitUntilFinished: true);
         List<Exception> errors = jobManager.Errors(job);
         if (errors != null || errors.Count > 0)
         {
             AttachConsole(-1);
             foreach (Exception error in errors)
                 Console.Write(error.ToString());
         }
         return true;
     }
     return false;
 }
예제 #7
0
    /// <summary>
    /// Adding a weekly reminder
    /// </summary>
    /// <param name="id">Id of the reminder</param>
    /// <param name="dayOfWeek">Day of the week</param>
    /// <param name="postTime">Post time</param>
    /// <param name="deletionTime">Deletion time</param>
    public void AddWeeklyReminder(long id, DayOfWeek dayOfWeek, TimeSpan postTime, TimeSpan deletionTime)
    {
        var postTimeStamp = DateTime.Today.Add(postTime);

        while (postTimeStamp < DateTime.Now ||
               postTimeStamp.DayOfWeek != dayOfWeek)
        {
            postTimeStamp = postTimeStamp.AddDays(1);
        }

        JobManager.AddJob(new WeeklyReminderPostJob(id),
                          obj => obj.ToRunOnceAt(postTimeStamp).AndEvery(7).Days().At(postTime.Hours, postTime.Minutes));

        var deletionTimeStamp = DateTime.Today.Add(deletionTime);

        while (deletionTimeStamp < DateTime.Now ||
               deletionTimeStamp.DayOfWeek != dayOfWeek)
        {
            deletionTimeStamp = deletionTimeStamp.AddDays(1);
        }

        JobManager.AddJob(new WeeklyReminderDeletionJob(id),
                          obj => obj.ToRunOnceAt(deletionTimeStamp).AndEvery(7).Days().At(postTime.Hours, postTime.Minutes));
    }
예제 #8
0
        /// <summary>
        /// 任务注册
        /// </summary>
        private void RegistryTask()
        {
            var time = CoreEngine.Current.AppSetting.GetAutoSetTime();

            JobManager.AddJob(() => {
                SuperEngine.Current.ReloadBackground?.Invoke(false, false);
            }, (s) => s
                              //.ToRunOnceAt(0, 30)
                              //.AndEvery(6)
                              //.Hours();
                              .ToRunEvery(1)
                              .Days()
                              .At(time.hour, time.minute));//.At(9, 15);

            JobManager.AddJob(() => {
                CoreEngine.Current.SetWallpaperAsync();
            }, (s) => s
                              //.ToRunOnceAt(0, 30)
                              //.AndEvery(6)
                              //.Hours();
                              .ToRunEvery(1)
                              .Days()
                              .At(time.hour, time.minute + 2));//.At(9, 15);
        }
예제 #9
0
        /// <summary>
        /// Main program entry point.
        /// </summary>
        /// <param name="args"> Command line arguments</param>
        /// <returns> Program exit code (0 for success)</returns>
        public static int Main(string[] args)
        {
            int exitCode = 0;

            try
            {
                string fileName          = null;
                string commandLineSwitch = null;

                // Check the command line arguments.
                if (args.Length >= 1)
                {
                    fileName = args[0];
                }

                if (args.Length == 2)
                {
                    commandLineSwitch = args[1];
                }

                if (args.Length < 1 || args.Length > 4)
                {
                    throw new Exception("Usage: ApsimX ApsimXFileSpec [/Recurse] [/Network] [/IP:<server IP>]");
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();

                if (commandLineSwitch == "/SingleThreaded")
                {
                    RunSingleThreaded(fileName);
                }

                else if (args.Contains("/Network"))
                {
                    try
                    {
                        int indexOfIPArgument = -1;
                        for (int i = 0; i < args.Length; i++)
                        {
                            if (args[i].Contains("IP"))
                            {
                                indexOfIPArgument = i;
                                break;
                            }
                        }

                        if (indexOfIPArgument == -1)
                        {
                            throw new Exception("/Network specified, but no IP given (/IP:<server IP>]");
                        }

                        DoNetworkRun(fileName, args[indexOfIPArgument].Split(':')[1], args.Contains("/Recurse")); // send files over network
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("Connection to server terminated.");
                    }
                }
                else
                {
                    // Create a instance of a job that will go find .apsimx files. Then
                    // pass the job to a job runner.
                    RunDirectoryOfApsimFiles runApsim = new RunDirectoryOfApsimFiles();
                    runApsim.FileSpec  = fileName;
                    runApsim.DoRecurse = args.Contains("/Recurse");
                    JobManager jobManager = new JobManager();
                    jobManager.AddJob(runApsim);
                    jobManager.Start(waitUntilFinished: true);

                    if (runApsim.JobsRanOK())
                    {
                        exitCode = 0;
                    }
                    else
                    {
                        exitCode = 1;
                    }
                }

                timer.Stop();
                Console.WriteLine("Finished running simulations. Duration " + timer.Elapsed.TotalSeconds.ToString("#.00") + " sec.");
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                exitCode = 1;
            }

            return(exitCode);
        }
예제 #10
0
파일: Project.cs 프로젝트: hut104/ApsimX
        /// <summary>
        /// Main program entry point.
        /// </summary>
        /// <param name="args"> Command line arguments</param>
        /// <returns> Program exit code (0 for success)</returns>
        public static int Main(string[] args)
        {
            int exitCode = 0 ;
            try
            {
                string fileName = null;
                string commandLineSwitch = null;

                // Check the command line arguments.
                if (args.Length >= 1)
                {
                    fileName = args[0];
                }

                if (args.Length == 2)
                {
                    commandLineSwitch = args[1];
                }

                if (args.Length < 1 || args.Length > 4)
                {
                    throw new Exception("Usage: ApsimX ApsimXFileSpec [/Recurse] [/Network] [/IP:<server IP>]");
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();

                if (commandLineSwitch == "/SingleThreaded")
                    RunSingleThreaded(fileName);

                else if (args.Contains("/Network"))
                {
                    try
                    {
                        int indexOfIPArgument = -1;
                        for (int i = 0; i < args.Length; i++)
                        {
                            if (args[i].Contains("IP"))
                            {
                                indexOfIPArgument = i;
                                break;
                            }
                        }

                        if (indexOfIPArgument == -1)
                        {
                            throw new Exception("/Network specified, but no IP given (/IP:<server IP>]");
                        }

                        DoNetworkRun(fileName, args[indexOfIPArgument].Split(':')[1], args.Contains("/Recurse")); // send files over network
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("Connection to server terminated.");
                    }
                }
                else
                {
                    // Create a instance of a job that will go find .apsimx files. Then
                    // pass the job to a job runner.
                    JobManager.IRunnable job;
                    if (fileName.Contains('*') || fileName.Contains('?'))
                        job = Runner.ForFolder(fileName, args.Contains("/Recurse"));
                    else
                        job = Runner.ForFile(fileName);
                    JobManager jobManager = new JobManager();
                    jobManager.AddJob(job);
                    jobManager.Start(waitUntilFinished: true);

                    if (jobManager.SomeHadErrors)
                    {
                        Console.WriteLine(job.ErrorMessage);
                        exitCode = 1;
                    }
                    else
                        exitCode = 0;
                }

                timer.Stop();
                Console.WriteLine("Finished running simulations. Duration " + timer.Elapsed.TotalSeconds.ToString("#.00") + " sec.");
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                exitCode = 1;
            }

            if (exitCode != 0)
                Console.WriteLine("ERRORS FOUND!!");
            return exitCode;
        }
예제 #11
0
 private void ScheduleJobs()
 {
     // TODO: Comments to explain reasoning behind times chosen, e.g. what are the Ops Team's deadlines for approval?
     JobManager.AddJob(RemindBillablePeopleJob, s => s.ToRunOnceAt(10, 0));
 }
        public void SchedulePlaytestAnnouncements(PlaytestEvent testEvent)
        {
            //If the test is null, likely only when first starting, abort.
            if (testEvent == null)
            {
                return;
            }

            if (_dataService.RSettings.ProgramSettings.Debug)
            {
                _ = _log.LogMessage($"SchedulePlaytestAnnouncements for {testEvent.Title}", false, color: LOG_COLOR);
            }

            var game = testEvent.Game.ToString();

            //Clear old jobs, if any.
            ClearScheduledAnnouncements(game);

            if (!testEvent.IsValid)
            {
                return;
            }

            var startDateTime = testEvent.StartDateTime;

            _ = _log.LogMessage($"Playtest of {testEvent.Title} scheduled for: {startDateTime}", false,
                                color: LOG_COLOR);

            if (startDateTime != null && DateTime.Compare(DateTime.Now.AddMinutes(60), startDateTime.Value) < 0)
            {
                //Subtract 60.2 minutes. If .2 isn't added the announcement states wrong time.
                JobManager.AddJob(async() => await PlaytestStartingInTask(testEvent), s => s
                                  .WithName($"[Playtest1Hour_{game}]").ToRunOnceAt(startDateTime.Value.AddMinutes(-60.2)));

                _ = _log.LogMessage("1 hour playtest announcement scheduled for:" +
                                    $"\n{JobManager.GetSchedule($"[Playtest1Hour_{game}]").NextRun}", false,
                                    color: LOG_COLOR);
            }

            if (startDateTime != null && DateTime.Compare(DateTime.Now.AddMinutes(20), startDateTime.Value) < 0)
            {
                JobManager.AddJob(async() => await PlaytestTwentyMinuteTask(testEvent), s => s
                                  .WithName($"[Playtest20Minute_{game}]").ToRunOnceAt(startDateTime.Value.AddMinutes(-20)));

                _ = _log.LogMessage("20 minute playtest announcement scheduled for:" +
                                    $"\n{JobManager.GetSchedule($"[Playtest20Minute_{game}]").NextRun}", false,
                                    color: LOG_COLOR);
            }

            if (startDateTime != null && DateTime.Compare(DateTime.Now.AddMinutes(15), startDateTime.Value) < 0)
            {
                JobManager.AddJob(async() => await PlaytestFifteenMinuteTask(testEvent), s => s
                                  .WithName($"[Playtest15Minute_{game}]").ToRunOnceAt(startDateTime.Value.AddMinutes(-15)));

                _ = _log.LogMessage("15 minute playtest announcement scheduled for:" +
                                    $"\n{JobManager.GetSchedule($"[Playtest15Minute_{game}]").NextRun}", false,
                                    color: LOG_COLOR);
            }

            if (startDateTime != null && DateTime.Compare(DateTime.Now, startDateTime.Value) < 0)
            {
                JobManager.AddJob(async() => await PlaytestStartingTask(testEvent), s => s
                                  .WithName($"[PlaytestStarting_{game}]").ToRunOnceAt(startDateTime.Value));

                _ = _log.LogMessage("Starting playtest announcement scheduled for:" +
                                    $"\n{JobManager.GetSchedule($"[PlaytestStarting_{game}]").NextRun}", false,
                                    color: LOG_COLOR);
            }
        }
예제 #13
0
 public void ScheduleJobOnce(string jobID, DateTime time, Action job)
 {
     JobManager.AddJob(job, (x) => x.WithName(jobID).ToRunOnceAt(time));
 }
예제 #14
0
 public void Schedule()
 {
     JobManager.AddJob(this, s => s.WithName(nameof(NewsJob)).ToRunEvery(0).Hours().At(0).Between(9, 0, 21, 0));
 }
예제 #15
0
        public void Process(SaveKpiTransformationScheduleResponse kpiTransformationSchedule)
        {
            var action = new DSLNG.PEAR.Data.Entities.BaseAction {
                UserId         = kpiTransformationSchedule.UserId,
                ControllerName = kpiTransformationSchedule.ControllerName,
                ActionName     = kpiTransformationSchedule.ActionName
            };
            var kpiPattern = @"k(\d+)";

            JobManager.AddJob(() =>
            {
                var complete = true;
                using (var dataContext = new DataContext())
                {
                    var kpiAchievementService            = new KpiAchievementService(dataContext);
                    var logService                       = new KpiTransformationLogService(dataContext);
                    var kpiTransformationScheduleService = new KpiTransformationScheduleService(dataContext);
                    var kpiService                       = new KpiService(dataContext);
                    #region loop date
                    foreach (var kpi in kpiTransformationSchedule.SelectedKpis)
                    {
                        for (var date = kpiTransformationSchedule.Start; date <= kpiTransformationSchedule.End; date = Increment(kpiTransformationSchedule, date))
                        {
                            try
                            {
                                var kpiTransformed    = kpi.CustomFormula;
                                var ytdTransformed    = kpi.CustomFormula;
                                var mtdTransformed    = kpi.CustomFormula;
                                var itdTransformed    = kpi.CustomFormula;
                                var existingKpiActual = kpiAchievementService.GetKpiAchievement(kpi.Id, date, kpiTransformationSchedule.PeriodeType);
                                // exception. could not be run because data dependency not found before Sept 30, 2016
                                // di remark kembali karena permintaan tanggal 25 Januari 2017, see Telegram
                                //if ((kpi.Id == 37 || kpi.Id == 8) && date < new DateTime(2016, 09, 30))
                                //{
                                //    continue;
                                //}
                                // pilih yang methodnya formula
                                if (kpi.MethodId == 1)
                                {
                                    if (string.IsNullOrEmpty(kpi.CustomFormula))
                                    {
                                        //log here for dependency error
                                        var logRequest = new SaveKpiTransformationLogRequest
                                        {
                                            KpiId = kpi.Id,
                                            KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                            Periode = date,
                                            Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                            Notes   = "Method input is formula but the formula is not defined"
                                        };
                                        logService.Save(logRequest);
                                        continue;
                                    }
                                    Regex r = new Regex(kpiPattern, RegexOptions.IgnoreCase);
                                    Match m = r.Match(kpi.CustomFormula);
                                    var meetRequirements = true;
                                    while (m.Success)
                                    {
                                        Group g              = m.Groups[1];
                                        var relatedKpiId     = int.Parse(g.Value);
                                        var relatedKpiActual = kpiAchievementService.GetKpiAchievement(relatedKpiId, date, kpiTransformationSchedule.PeriodeType);
                                        if (relatedKpiActual.IsSuccess && relatedKpiActual.Value.HasValue)
                                        {
                                            kpiTransformed = Regex.Replace(kpiTransformed, "k" + g.Value, (relatedKpiActual.Value % 1) == 0 ? relatedKpiActual.Value.ToString() + ".00" : relatedKpiActual.Value.ToString(), RegexOptions.IgnoreCase);
                                            if (kpi.YtdFormula == YtdFormula.Custom)
                                            {
                                                if ((relatedKpiActual.Mtd.HasValue && relatedKpiActual.Ytd.HasValue && relatedKpiActual.Itd.HasValue && kpiTransformationSchedule.PeriodeType == PeriodeType.Daily) ||
                                                    (relatedKpiActual.Ytd.HasValue && relatedKpiActual.Itd.HasValue && kpiTransformationSchedule.PeriodeType == PeriodeType.Monthly) ||
                                                    (relatedKpiActual.Itd.HasValue && kpiTransformationSchedule.PeriodeType == PeriodeType.Yearly))
                                                {
                                                    switch (kpiTransformationSchedule.PeriodeType)
                                                    {
                                                    case PeriodeType.Daily:
                                                        mtdTransformed = Regex.Replace(mtdTransformed, "k" + g.Value, relatedKpiActual.Mtd.ToString(), RegexOptions.IgnoreCase);
                                                        ytdTransformed = Regex.Replace(ytdTransformed, "k" + g.Value, relatedKpiActual.Ytd.ToString(), RegexOptions.IgnoreCase);
                                                        itdTransformed = Regex.Replace(itdTransformed, "k" + g.Value, relatedKpiActual.Itd.ToString(), RegexOptions.IgnoreCase);
                                                        break;

                                                    case PeriodeType.Monthly:
                                                        ytdTransformed = Regex.Replace(ytdTransformed, "k" + g.Value, relatedKpiActual.Ytd.ToString(), RegexOptions.IgnoreCase);
                                                        itdTransformed = Regex.Replace(itdTransformed, "k" + g.Value, relatedKpiActual.Itd.ToString(), RegexOptions.IgnoreCase);
                                                        break;

                                                    case PeriodeType.Yearly:
                                                        itdTransformed = Regex.Replace(itdTransformed, "k" + g.Value, relatedKpiActual.Itd.ToString(), RegexOptions.IgnoreCase);
                                                        break;

                                                    default:
                                                        break;
                                                    }
                                                }
                                                else
                                                {
                                                    //log here for dependency error
                                                    var logRequest = new SaveKpiTransformationLogRequest
                                                    {
                                                        KpiId = kpi.Id,
                                                        KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                        Periode = date,
                                                        Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                        Notes   = "The aggregation for <strong>" + relatedKpiActual.Kpi.Name + " (" + relatedKpiActual.Kpi.Measurement + ")</strong> has not been proceed"
                                                    };
                                                    logService.Save(logRequest);
                                                    meetRequirements = false;
                                                    complete         = false;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            var relatedKpi = kpiService.GetBy(new Services.Requests.Kpi.GetKpiRequest {
                                                Id = relatedKpiId
                                            });
                                            var logRequest = new SaveKpiTransformationLogRequest
                                            {
                                                KpiId = kpi.Id,
                                                KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                Periode = date,
                                                Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                Notes   = "Kpi <strong>" + relatedKpi.Name + " (" + relatedKpi.Measurement.Name + ")</strong> has no value for this periode of time"
                                            };
                                            logService.Save(logRequest);
                                            meetRequirements = false;
                                            complete         = false;
                                        }
                                        m = m.NextMatch();
                                    }
                                    if (kpi.YtdFormula == YtdFormula.Custom)
                                    {
                                        if (meetRequirements)
                                        {
                                            var kpiActualRequest = new UpdateKpiAchievementItemRequest
                                            {
                                                Id             = existingKpiActual.IsSuccess ? existingKpiActual.Id : 0,
                                                KpiId          = kpi.Id,
                                                Periode        = date,
                                                PeriodeType    = kpiTransformationSchedule.PeriodeType,
                                                Value          = null,
                                                UserId         = kpiTransformationSchedule.UserId,
                                                ControllerName = action.ControllerName,
                                                ActionName     = action.ActionName
                                            };

                                            if (kpiTransformed != kpi.CustomFormula)
                                            {
                                                var val = new Expression(kpiTransformed).Evaluate().ToString();
                                                if (!Double.IsInfinity(double.Parse(val)) && !Double.IsNaN(double.Parse(val)))
                                                {
                                                    kpiActualRequest.Value = val; //new Expression(kpiTransformed).Evaluate().ToString();
                                                }
                                                else
                                                {
                                                    var logRequest = new SaveKpiTransformationLogRequest
                                                    {
                                                        KpiId = kpi.Id,
                                                        KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                        Periode = date,
                                                        Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                        Notes   = "Infinite Result",
                                                        NeedCleanRowWhenError = true
                                                    };
                                                    logService.Save(logRequest);
                                                    complete = false;
                                                    continue;
                                                }
                                            }
                                            if (mtdTransformed != kpi.CustomFormula)
                                            {
                                                var val = double.Parse(new Expression(mtdTransformed).Evaluate().ToString());
                                                if (!Double.IsInfinity(val) && !Double.IsNaN(val))
                                                {
                                                    kpiActualRequest.Mtd = val;
                                                }
                                                else
                                                {
                                                    var logRequest = new SaveKpiTransformationLogRequest
                                                    {
                                                        KpiId = kpi.Id,
                                                        KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                        Periode = date,
                                                        Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                        Notes   = "Infinite Result",
                                                        NeedCleanRowWhenError = true
                                                    };
                                                    logService.Save(logRequest);
                                                    complete = false;
                                                    continue;
                                                }
                                            }
                                            if (ytdTransformed != kpi.CustomFormula)
                                            {
                                                var ytd = double.Parse(new Expression(ytdTransformed).Evaluate().ToString());
                                                if (!Double.IsInfinity(ytd) && !Double.IsNaN(ytd))
                                                {
                                                    kpiActualRequest.Ytd = ytd;
                                                }
                                                else
                                                {
                                                    var logRequest = new SaveKpiTransformationLogRequest
                                                    {
                                                        KpiId = kpi.Id,
                                                        KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                        Periode = date,
                                                        Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                        Notes   = "Infinite Result",
                                                        NeedCleanRowWhenError = true
                                                    };
                                                    logService.Save(logRequest);
                                                    complete = false;
                                                    continue;
                                                }
                                            }
                                            if (itdTransformed != kpi.CustomFormula)
                                            {
                                                var itd = double.Parse(new Expression(itdTransformed).Evaluate().ToString());
                                                if (!Double.IsInfinity(itd) && !Double.IsNaN(itd))
                                                {
                                                    kpiActualRequest.Itd = itd;
                                                }
                                                else
                                                {
                                                    var logRequest = new SaveKpiTransformationLogRequest
                                                    {
                                                        KpiId = kpi.Id,
                                                        KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                        Periode = date,
                                                        Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                        Notes   = "Infinite Result",
                                                        NeedCleanRowWhenError = true
                                                    };
                                                    logService.Save(logRequest);
                                                    complete = false;
                                                    continue;
                                                }
                                            }
                                            kpiActualRequest.UpdateDeviation = true;
                                            var resp = kpiAchievementService.UpdateKpiAchievementItem(kpiActualRequest);
                                            if (resp.IsSuccess)
                                            {
                                                var thatYear = new DateTime(date.Year, 1, 1);
                                                var existingYearKpiActual  = kpiAchievementService.GetKpiAchievement(kpi.Id, thatYear, PeriodeType.Yearly);
                                                var kpiactualYearlyRequest = new UpdateKpiAchievementItemRequest
                                                {
                                                    Id             = existingYearKpiActual.IsSuccess ? existingYearKpiActual.Id : 0,
                                                    KpiId          = kpi.Id,
                                                    Periode        = thatYear,
                                                    PeriodeType    = PeriodeType.Yearly,
                                                    Value          = kpiActualRequest.Ytd.ToString(),
                                                    UserId         = kpiTransformationSchedule.UserId,
                                                    Itd            = kpiActualRequest.Itd,
                                                    ControllerName = action.ControllerName,
                                                    ActionName     = action.ActionName
                                                };
                                                switch (kpiTransformationSchedule.PeriodeType)
                                                {
                                                case PeriodeType.Daily:
                                                    var theDate = new DateTime(date.Year, date.Month, 1);
                                                    var existingMonthlyKpiActual = kpiAchievementService.GetKpiAchievement(kpi.Id, theDate, PeriodeType.Monthly);

                                                    var kpiActualMonthlyRequest = new UpdateKpiAchievementItemRequest
                                                    {
                                                        Id             = existingMonthlyKpiActual.IsSuccess ? existingMonthlyKpiActual.Id : 0,
                                                        KpiId          = kpi.Id,
                                                        Periode        = theDate,
                                                        PeriodeType    = PeriodeType.Monthly,
                                                        Value          = kpiActualRequest.Mtd.ToString(),
                                                        UserId         = kpiTransformationSchedule.UserId,
                                                        Ytd            = kpiActualRequest.Ytd,
                                                        Itd            = kpiActualRequest.Itd,
                                                        ControllerName = action.ControllerName,
                                                        ActionName     = action.ActionName
                                                    };
                                                    kpiAchievementService.UpdateKpiAchievementItem(kpiActualMonthlyRequest);
                                                    //kpiAchievementService.UpdateKpiAchievementItem(kpi.Id, PeriodeType.Monthly, new DateTime(date.Year, date.Month, 1), kpiActualRequest.Mtd, kpiTransformationSchedule.UserId);
                                                    //kpiAchievementService.UpdateKpiAchievementItem(kpi.Id, PeriodeType.Yearly, new DateTime(date.Year, 1, 1), kpiActualRequest.Ytd, kpiTransformationSchedule.UserId);
                                                    kpiAchievementService.UpdateKpiAchievementItem(kpiactualYearlyRequest);
                                                    break;

                                                case PeriodeType.Monthly:
                                                    kpiAchievementService.UpdateKpiAchievementItem(kpiactualYearlyRequest);
                                                    //kpiAchievementService.UpdateKpiAchievementItem(kpi.Id, PeriodeType.Yearly, new DateTime(date.Year, 1, 1), kpiActualRequest.Ytd, kpiTransformationSchedule.UserId);
                                                    break;

                                                default:
                                                    break;
                                                }

                                                var logRequest = new SaveKpiTransformationLogRequest
                                                {
                                                    KpiId = kpi.Id,
                                                    KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                    Periode = date,
                                                    Status  = KpiTransformationStatus.Complete,
                                                };
                                                logService.Save(logRequest);
                                            }
                                            else
                                            {
                                                var logRequest = new SaveKpiTransformationLogRequest
                                                {
                                                    KpiId = kpi.Id,
                                                    KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                    Periode = date,
                                                    Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                    Notes   = resp.Message
                                                };
                                                logService.Save(logRequest);
                                                complete = false;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (meetRequirements)
                                        {
                                            var request = new UpdateKpiAchievementItemRequest
                                            {
                                                Periode        = date,
                                                PeriodeType    = kpiTransformationSchedule.PeriodeType,
                                                Id             = existingKpiActual.IsSuccess ? existingKpiActual.Id : 0,
                                                KpiId          = kpi.Id,
                                                UserId         = kpiTransformationSchedule.UserId,
                                                Value          = new Expression(kpiTransformed).Evaluate().ToString(),
                                                ControllerName = action.ControllerName,
                                                ActionName     = action.ActionName
                                            };
                                            var resp = kpiAchievementService.UpdateOriginalData(request);
                                            if (resp.IsSuccess)
                                            {
                                                //if(kpi.YtdFormula == YtdFormula.NaN)
                                                //{
                                                //    switch (kpiTransformationSchedule.PeriodeType)
                                                //    {
                                                //        case PeriodeType.Daily:
                                                //            kpiAchievementService.UpdateKpiAchievementItem(kpi.Id, PeriodeType.Monthly, new DateTime(date.Year, date.Month, 1), double.Parse(request.Value), kpiTransformationSchedule.UserId);
                                                //            kpiAchievementService.UpdateKpiAchievementItem(kpi.Id, PeriodeType.Yearly, new DateTime(date.Year, 1, 1), double.Parse(request.Value), kpiTransformationSchedule.UserId);
                                                //            break;
                                                //        case PeriodeType.Monthly:
                                                //            kpiAchievementService.UpdateKpiAchievementItem(kpi.Id, PeriodeType.Yearly, new DateTime(date.Year, 1, 1), double.Parse(request.Value), kpiTransformationSchedule.UserId);
                                                //            break;
                                                //        default:
                                                //            break;
                                                //    }
                                                //}
                                                var logRequest = new SaveKpiTransformationLogRequest
                                                {
                                                    KpiId = kpi.Id,
                                                    KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                    Periode = date,
                                                    Status  = KpiTransformationStatus.Complete,
                                                };
                                                logService.Save(logRequest);
                                            }
                                            else
                                            {
                                                var logRequest = new SaveKpiTransformationLogRequest
                                                {
                                                    KpiId = kpi.Id,
                                                    KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                                    Periode = date,
                                                    Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                                    Notes   = resp.Message
                                                };
                                                logService.Save(logRequest);
                                                complete = false;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    var request = new UpdateKpiAchievementItemRequest
                                    {
                                        Periode        = date,
                                        PeriodeType    = kpiTransformationSchedule.PeriodeType,
                                        Id             = existingKpiActual.IsSuccess ? existingKpiActual.Id : 0,
                                        KpiId          = kpi.Id,
                                        UserId         = kpiTransformationSchedule.UserId,
                                        Value          = existingKpiActual.Value.ToString(),
                                        Remark         = existingKpiActual.Remark,
                                        ControllerName = action.ControllerName,
                                        ActionName     = action.ActionName
                                    };
                                    var resp = kpiAchievementService.UpdateOriginalData(request);
                                    if (resp.IsSuccess)
                                    {
                                        if (date == kpiTransformationSchedule.End)
                                        {
                                        }
                                        var logRequest = new SaveKpiTransformationLogRequest
                                        {
                                            KpiId = kpi.Id,
                                            KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                            Periode = date,
                                            Status  = KpiTransformationStatus.Complete,
                                        };
                                        logService.Save(logRequest);
                                    }
                                    else
                                    {
                                        var logRequest = new SaveKpiTransformationLogRequest
                                        {
                                            KpiId = kpi.Id,
                                            KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                            Periode = date,
                                            Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                            Notes   = resp.Message
                                        };
                                        logService.Save(logRequest);
                                        complete = false;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                var logRequest = new SaveKpiTransformationLogRequest
                                {
                                    KpiId = kpi.Id,
                                    KpiTransformationScheduleId = kpiTransformationSchedule.Id, PeriodeType = kpiTransformationSchedule.PeriodeType,
                                    Periode = date,
                                    Status  = KpiTransformationStatus.Error, MethodId = kpi.MethodId,
                                    Notes   = string.Format("Excception Message :{0}<br/>Inner Exception Message : {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "")
                                };
                                logService.Save(logRequest);
                                complete = false;
                            }
                        }
                    }

                    if (complete)
                    {
                        kpiTransformationScheduleService.UpdateStatus(kpiTransformationSchedule.Id, KpiTransformationStatus.Complete);
                    }
                    else
                    {
                        kpiTransformationScheduleService.UpdateStatus(kpiTransformationSchedule.Id, KpiTransformationStatus.Error);
                    }

                    #endregion
                }
            }, (s) => s.ToRunNow());
        }
예제 #16
0
        private void ResetScheduledJob(JobType jobType, string time = "")
        {
            bool            settingsCondition = false;
            string          registryKey       = string.Empty;
            Func <Task>     job            = null;
            ScheduleDayTime settingsTime   = null;
            int             randomInterval = 0;
            string          period         = string.Empty;

            switch (jobType)
            {
            case JobType.Switch:
                settingsCondition = WtmSettings.AutoSwitch;
                registryKey       = Constants.SwitchRegistryKey;
                job    = (async() => await SwitchTaskWrapper().ConfigureAwait(false));
                period = WtmSettings.SwitchPeriod.TrimEnd('s');
                if (period == "Day")
                {
                    settingsTime = new ScheduleDayTime(WtmSettings.SwitchPeriodCount, WtmSettings.SwitchTimeFrom);
                }
                if (period == "Hour")
                {
                    settingsTime = new ScheduleDayTime(0, WtmSettings.SwitchPeriodCount, WtmSettings.SwitchTimeFrom.Minute);
                }
                randomInterval = ScheduleTime.Difference(WtmSettings.SwitchTimeTo, WtmSettings.SwitchTimeFrom);
                break;

            case JobType.UpdatePriceHistory:
                settingsCondition = WtmSettings.BackupHistoricalPrices;
                registryKey       = Constants.UpdatePriceHistoryRegistryKey;
                job            = (async() => await UpdatePriceHistoryTaskWrapper().ConfigureAwait(false));
                period         = "Day";
                settingsTime   = new ScheduleDayTime(1, WtmSettings.HistoryTimeFrom);
                randomInterval = ScheduleTime.Difference(WtmSettings.HistoryTimeTo, WtmSettings.HistoryTimeFrom);
                break;
            }
            JobManager.RemoveJob(jobType.ToString());
            if (settingsCondition)
            {
                DateTime scheduleTime = new DateTime();
                if (time != string.Empty) // Schedule job at given time. This branch is used when there's a pending job in registry after reboot.
                {
                    var pendingTime = Convert.ToDateTime(time, DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
                    if (pendingTime > DateTime.UtcNow)
                    {
                        scheduleTime = pendingTime;
                    }
                    else // Over-protection, should not actually happen?
                    {
                        SetRegistryKeyValue(registryKey, "Schedule", string.Empty);
                        ResetScheduledJob(jobType);
                        return;
                    }
                }
                else // Schedule job from current WtmSettings.SwitchTimeFrom. This branch is used when applying new settings.
                {
                    using (RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(registryKey, true))
                    {
                        DateTime now     = DateTime.Now;
                        DateTime newTime = new DateTime();
                        switch (period)
                        {
                        case "Day":
                            newTime = new DateTime(now.Year, now.Month, now.Day, settingsTime.Hour, settingsTime.Minute, 0, DateTimeKind.Local);
                            if (newTime < now)
                            {
                                newTime = newTime.AddDays(settingsTime.Day);
                            }
                            break;

                        case "Hour":
                            newTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, settingsTime.Minute, 0, DateTimeKind.Local);
                            if (newTime < now)
                            {
                                newTime = newTime.AddHours(settingsTime.Hour);
                            }
                            break;
                        }

                        scheduleTime = newTime.ToUniversalTime();
                        if (randomInterval > 0)
                        {
                            scheduleTime = scheduleTime.AddMinutes(Helpers.Random.Next(randomInterval));
                        }
                        regKey.SetValue("Schedule", scheduleTime.ToString("o"), RegistryValueKind.String);
                        if (jobType == JobType.Switch)
                        {
                            SwitchSchedule = scheduleTime.ToLocalTime();
                        }
                        if (jobType == JobType.UpdatePriceHistory)
                        {
                            HistoricalPricesSchedule = scheduleTime.ToLocalTime();
                        }
                    }
                }

                JobManager.AddJob(
                    async() =>
                {
                    await job().ConfigureAwait(false);
                    ResetScheduledJob(jobType);
                    if (WtmSettings.RestartComputer && RestartComputerPending)
                    {
                        Helpers.RestartComputer(5);
                    }
                },
                    (sch) => sch.WithName(jobType.ToString()).ToRunOnceAt(scheduleTime));
            }
            UpdateNextJobStatus();
        }
예제 #17
0
파일: Form1.cs 프로젝트: liwenhai/jdforme
 private void StartJobNow(Action job, int witchSecendToStart)
 {
     //开启定时任务
     JobManager.AddJob(job, t => { t.ToRunOnceIn(witchSecendToStart).Seconds(); });
 }
예제 #18
0
파일: Form1.cs 프로젝트: liwenhai/jdforme
 private static void StartJobNow(Action job, DateTime startTime)
 {
     //开启定时任务
     JobManager.AddJob(job, t => { t.ToRunOnceAt(startTime); });
 }
예제 #19
0
 public void Initialize()
 {
     JobManager.AddJob(async() => await PostAllServerInfoAsync().ConfigureAwait(false), (x) => x.ToRunNow().AndEvery(1).Minutes());
 }
예제 #20
0
        private void StartPaiMaiJob(string paimaiId, int myPrice)
        {
            //获取拍卖信息
            var paimaiItemDetail =
                GetPaiMaiDetailListFromWeb(new List <PaimaiItem> {
                new PaimaiItem {
                    paimaiId = paimaiId
                }
            }).Single();

            if (paimaiItemDetail == null)
            {
                AddLog("\n" + "查询失败退出StartPaiMaiJob" + GetNow());
                return;
            }


            //设置拍卖结束时间为拍卖的开始时间
            var startTime = ConvertIntDateTime(paimaiItemDetail.endTime);
            //AddLog("\n" + "设定拍卖开始时间" + getNow());
            //判定登陆的帐号数目
            var i = 0;

            //每个帐号间隔80毫秒进行拍卖操作
            _accountsList.ForEach(account =>
            {
                //开启定时任务

                JobManager.AddJob(() =>
                {
                    //AddLog("\n" + "开始竞拍:" + paimaiId + " " + getNow());
                    StartPaimai(paimaiId, myPrice, account, Config.zeroTimeForPaimai * i + 80);
                }, t =>
                {
                    //t.ToRunNow().AndEvery(1).Seconds();
                    //提前多久开始出价
                    _scheduleAndPaimaiInfo.Add(t, paimaiItemDetail);
                    t.WithName(GetPaiMaiJobName(paimaiId))
                    .ToRunOnceAt(
                        startTime.AddMilliseconds(-Config.beforeBeginTime));
                });
                i++;
            });

            //拍卖结束后执行保存拍卖数据操作,并做统计
            JobManager.AddJob(() =>
            {
                var finishResult =
                    GetPaiMaiDetailListFromWeb(new List <PaimaiItem> {
                    new PaimaiItem {
                        paimaiId = paimaiId
                    }
                }).Single();
                if (finishResult == null)
                {
                    AddLog("\n" + "查询失败退出:JobManager.AddJob" + "拍卖结束后执行保存拍卖数据操作");
                    return;
                }

                //AddLog("\n" + "开始竞拍:" + paimaiId + " " + getNow());
                //保存拍卖明细
                SavePaimaiDetail(finishResult);
                if (finishResult.auctionStatus == (int)EnumType.AuctionStatus.EndAuction)
                {
                    CalculateProductInfo(finishResult);
                }
            }, t => { t.ToRunOnceAt(startTime.AddMilliseconds(5)); });
        }
예제 #21
0
        private async Task MainAsync()
        {
            var startupStr = string.Format("Bot starting up. ({0} by Michael Flaherty)", Program.VERSION);

            await Log(new LogMessage(LogSeverity.Info, "Startup", startupStr));

            var socketConfig = new DiscordSocketConfig
            {
                WebSocketProvider = WS4NetProvider.Instance,
                LogLevel          = LogSeverity.Verbose
            };

            client   = new DiscordSocketClient(socketConfig);
            commands = new CommandService();
            services = new ServiceCollection().BuildServiceProvider();

            messageHist = new Dictionary <ulong, List <MsgInfo> >();
            triggerMap  = new Dictionary <ulong, string>();
            markov      = new MarkovHandler();
            facts       = new FactHandler();
            random      = new Random();

            client.Log            += Log;
            client.GuildAvailable += OnGuildAvailable;

            client.MessageReceived += HandleCommand;
            await commands.AddModulesAsync(Assembly.GetEntryAssembly());

            await client.LoginAsync(TokenType.Bot, config.DiscordBotToken);

            await client.StartAsync();

            // Connect to steam and pump callbacks
            connection = new SteamConnection(config.SteamUsername, config.SteamPassword);
            connection.Connect();

            if (config.GitHubUpdateRepository.Length != 0 && config.GitHubAuthToken.Length != 0)
            {
                ghClient             = new GitHubClient(new ProductHeaderValue(Program.config.GitHubUpdateRepository));
                ghClient.Credentials = new Credentials(config.GitHubAuthToken);
            }

            // Handle Jobs
            manager = new JobManager(config.JobInterval); // time in seconds to run each job
            if (config.SelfUpdateListener && config.GitHubAuthToken.Length != 0)
            {
                manager.AddJob(new SelfUpdateListener());
            }
            if (config.SteamCheckJob)
            {
                manager.AddJob(new SteamCheckJob(connection));
            }
            if (config.AlliedModdersThreadJob)
            {
                manager.AddJob(new AlliedModdersThreadJob("https://forums.alliedmods.net/external.php?newpost=true&forumids=108", "sourcemod"));
            }

            foreach (uint appid in config.AppIDList)
            {
                manager.AddJob(new UpdateJob(appid));
            }

            manager.StartJobs();

            await Task.Delay(-1);
        }
예제 #22
0
        public async Task <Version?> CheckAndUpdateAsync(bool withTimer)
        {
            if (!Core.IsNetworkAvailable)
            {
                return(null);
            }

            if (!Core.Config.AutoUpdates)
            {
                Logger.Log("Updates are disabled.", LogLevels.Trace);
                return(null);
            }

            await UpdateSemaphore.WaitAsync().ConfigureAwait(false);

            Logger.Log("Checking for any new version...", LogLevels.Trace);

            try {
                await Github.Request().ConfigureAwait(false);

                string?gitVersion = Github.ReleaseTagName;

                if (string.IsNullOrEmpty(gitVersion))
                {
                    Logger.Warning("Failed to request version information.");
                    return(null);
                }

                if (!Version.TryParse(gitVersion, out Version? LatestVersion))
                {
                    Logger.Log("Could not parse the version. Make sure the version is correct at Github project repo.", LogLevels.Warn);
                    return(null);
                }

                UpdateAvailable = LatestVersion > Constants.Version;
                IsOnPrerelease  = LatestVersion < Constants.Version;

                if (!UpdateAvailable)
                {
                    if (IsOnPrerelease)
                    {
                        Logger.Log("Seems like you are on a pre-release channel. please report any bugs you encounter!", LogLevels.Warn);
                    }

                    Logger.Log($"You are up to date! ({LatestVersion}/{Constants.Version})");

                    if (withTimer)
                    {
                        if (JobManager.GetSchedule(JOB_NAME) == null)
                        {
                            JobManager.AddJob(async() => await CheckAndUpdateAsync(withTimer).ConfigureAwait(false), (s) => s.WithName(JOB_NAME).ToRunEvery(1).Days().At(00, 00));
                            Logger.Info("Assistant will check for updates every 24 hours.");
                        }
                    }

                    return(LatestVersion);
                }

                if (IsOnPrerelease)
                {
                    Logger.Log("Seems like you are on a pre-release channel. please report any bugs you encounter!", LogLevels.Warn);
                    return(LatestVersion);
                }

                Logger.Log($"New version available!", LogLevels.Green);
                Logger.Log($"Latest Version: {LatestVersion} / Local Version: {Constants.Version}");
                Logger.Log("Automatically updating in 10 seconds...", LogLevels.Warn);
                ExecuteAsyncEvent <IEvent>(MODULE_EXECUTION_CONTEXT.UpdateAvailable, default);
                Helpers.ScheduleTask(async() => await InitUpdate().ConfigureAwait(false), TimeSpan.FromSeconds(10));
                return(LatestVersion);
            }
            catch (Exception e) {
                Logger.Exception(e);
                return(null);
            }
            finally {
                UpdateSemaphore.Release();
            }
        }
예제 #23
0
파일: Project.cs 프로젝트: debunge/ApsimX
        /// <summary>
        /// Main program entry point.
        /// </summary>
        /// <param name="args"> Command line arguments</param>
        /// <returns> Program exit code (0 for success)</returns>
        public static int Main(string[] args)
        {
            string tempFolder = Path.Combine(Path.GetTempPath(), "ApsimX");

            Directory.CreateDirectory(tempFolder);
            Environment.SetEnvironmentVariable("TMP", tempFolder, EnvironmentVariableTarget.Process);
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Manager.ResolveManagerAssembliesEventHandler);

            int exitCode = 0;

            try
            {
                string fileName          = null;
                string commandLineSwitch = null;

                // Check the command line arguments.
                if (args.Length >= 1)
                {
                    fileName = args[0];
                }

                if (args.Length == 2)
                {
                    commandLineSwitch = args[1];
                }

                if (args.Length < 1 || args.Length > 4)
                {
                    throw new Exception("Usage: ApsimX ApsimXFileSpec [/Recurse] [/Network] [/IP:<server IP>]");
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();

                if (commandLineSwitch == "/SingleThreaded")
                {
                    RunSingleThreaded(fileName);
                }

                else if (args.Contains("/Network"))
                {
                    try
                    {
                        int indexOfIPArgument = -1;
                        for (int i = 0; i < args.Length; i++)
                        {
                            if (args[i].Contains("IP"))
                            {
                                indexOfIPArgument = i;
                                break;
                            }
                        }

                        if (indexOfIPArgument == -1)
                        {
                            throw new Exception("/Network specified, but no IP given (/IP:<server IP>]");
                        }

                        DoNetworkRun(fileName, args[indexOfIPArgument].Split(':')[1], args.Contains("/Recurse")); // send files over network
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("Connection to server terminated.");
                    }
                }
                else
                {
                    // Create a instance of a job that will go find .apsimx files. Then
                    // pass the job to a job runner.
                    JobManager.IRunnable job;
                    if (fileName.Contains('*') || fileName.Contains('?'))
                    {
                        job = Runner.ForFolder(fileName, args.Contains("/Recurse"), args.Contains("/RunTests"));
                    }
                    else
                    {
                        job = Runner.ForFile(fileName, args.Contains("/RunTests"));
                    }
                    JobManager jobManager = new JobManager();
                    jobManager.AddJob(job);
                    jobManager.Start(waitUntilFinished: true);

                    List <Exception> errors = jobManager.Errors(job);
                    if (errors.Count > 0)
                    {
                        errors.ForEach(e => Console.WriteLine(e.ToString() + Environment.NewLine));
                        exitCode = 1;
                    }
                    else
                    {
                        exitCode = 0;
                    }
                }

                timer.Stop();
                Console.WriteLine("Finished running simulations. Duration " + timer.Elapsed.TotalSeconds.ToString("#.00") + " sec.");
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                exitCode = 1;
            }

            if (exitCode != 0)
            {
                Console.WriteLine("ERRORS FOUND!!");
            }
            return(exitCode);
        }
예제 #24
0
 /// <summary>
 /// Run IExtracter every x minutes
 /// </summary>
 /// <param name="extracter"></param>
 /// <param name="periodicTime"></param>
 public void Add(IExtracter extracter, int periodicTime)
 {
     JobManager.AddJob(extracter, s => s.ToRunNow().AndEvery(periodicTime).Minutes());
 }
예제 #25
0
        private void SendButtonClick(object sender, RoutedEventArgs e)
        {
            if (toTextBox.Text == string.Empty || themeText.Text == string.Empty)
            {
                MessageBox.Show("Fill in all fields to send a message!");
                return;
            }

            if (TypeComboBox.SelectedValue == null)
            {
                MessageBox.Show("Select the period of sending messages!");
                return;
            }

            if (!TimeSpan.TryParse(startTime.Text, out TimeSpan timeStart))
            {
                MessageBox.Show("Start time is not filled correctly!");
                return;
            }

            if (!TimeSpan.TryParse(startTime.Text, out TimeSpan timeEnd))
            {
                MessageBox.Show("End time is not correct!");
                return;
            }

            if (startDate.SelectedDate.Value.AddHours(timeStart.Hours).AddMinutes(timeStart.Minutes) < DateTime.Now)
            {
                MessageBox.Show("Date of starting the operation of sending a message should not be less than the current date!");
                return;
            }

            if (endDate.SelectedDate.Value.AddHours(timeEnd.Hours).AddMinutes(timeEnd.Minutes) < startDate.SelectedDate.Value.AddHours(timeStart.Hours).AddMinutes(timeStart.Minutes))
            {
                MessageBox.Show("The date of the end of the message sending operation should not be less than the start date!");
                return;
            }

            const int INTERVAL   = 1;
            var       periodType = (Types)TypeComboBox.SelectedValue;

            string jobName = "";

            if (periodType == Types.Day)
            {
                jobName = "DayJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Days().At(timeStart.Hours, timeStart.Minutes));
            }
            else if (periodType == Types.Week)
            {
                jobName = "WeekJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Weeks().On(DayOfWeek.Monday).At(timeStart.Hours, timeStart.Minutes));
            }
            else if (periodType == Types.Month)
            {
                jobName = "MonthJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Months().OnTheFirst(DayOfWeek.Monday).At(timeStart.Hours, timeStart.Minutes));
            }
            else if (periodType == Types.Year)
            {
                jobName = "YearJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Years().On(1).At(timeStart.Hours, timeStart.Minutes));
            }

            if (startDate.DisplayDate == DateTime.Now.Date)
            {
                JobManager.Start();
            }

            if (endDate.SelectedDate.Value.AddHours(timeEnd.Hours).AddMinutes(timeEnd.Minutes) == DateTime.Now.Date)
            {
                JobManager.Stop();
                JobManager.RemoveJob(jobName);
            }
        }
예제 #26
0
 /// <summary>
 /// Starts the Console title updater job and updates the title every 1 second.
 /// </summary>
 /// <returns>The <see cref="Core"/></returns>
 public Core StartConsoleTitleUpdater()
 {
     JobManager.AddJob(() => SetConsoleTitle(), (s) => s.WithName("ConsoleUpdater").ToRunEvery(1).Seconds());
     return(this);
 }
예제 #27
0
        public override void Execute()
        {
            Log.Information("Job retrieval job starting");

            var jobApprovalLogic = new JobApprovalLogic(_userRetriever);
            int offset           = 0;
            int runin            = 5;
            List <JobStatus> statusesToProcess = new List <JobStatus>()
            {
                JobStatus.ToBeProcessed, JobStatus.PreApproved, JobStatus.Approved
            };

            try
            {
                bool requestIsValid   = true;
                var  requestsToUpdate = new List <WikiJobRequest>();
                //Get job definitions
                var requests = _jobRetriever.JobDefinitions?.Where(request => statusesToProcess.Contains(request.Status)).ToList();

                if (requests != null && requests.Count > 0)
                {
                    Log.Information($"Processing {requests.Count} requests");
                    foreach (WikiJobRequest request in requests)
                    {
                        Log.Information($"Processing retrieved request: {request.RawRequest}");
                        try
                        {
                            requestIsValid = true;
                            if (request.Status == JobStatus.ToBeProcessed)
                            {
                                Log.Information("Request is ToBeProcessed");
                                //Check For Automatic Approval
                                CheckForUserApproval(request, jobApprovalLogic);

                                //Save Job
                                JobData.SaveWikiJobRequest(request);

                                //Add to update list
                                requestsToUpdate.Add(request);
                            }
                            else
                            {
                                Log.Information("Request has been previously approved or preapproved");
                                var existingRequest = JobData.GetWikiJobRequestByID(request.ID);
                                requestIsValid = requestIsValid && request.RawRequest.Equals(existingRequest.RawRequest);
                                Log.Information($"Existing request {existingRequest.RawRequest} equals is {requestIsValid}");
                            }

                            if (requestIsValid && (request.Status == JobStatus.Approved || request.Status == JobStatus.PreApproved))
                            {
                                Log.Information("Scheduling request");
                                //Schedule jobs in 10 minute intervals
                                //How to deal with potential page edit overlaps? -> Check page lists and id overlaps;
                                var job = WikiJobFactory.GetWikiJob(request, Log, _wikiAccessLogic, Configuration, JobData, _jobRetriever);
                                JobManager.AddJob(() => job.Execute(), (s) => s.ToRunOnceIn(runin + offset).Minutes());
                                offset = offset + 10;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, $"Error processing request {request.RawRequest}:");
                        }
                    }

                    Log.Information("Saving requests");
                    //Update job status on the wiki page the job was retreived from
                    _jobRetriever.UpdateRequests(requestsToUpdate);
                }
                else
                {
                    Log.Information("No requests found.");
                }
                string keepAliveURL = Configuration["KeepAliveURL"];
                if (!string.IsNullOrEmpty(keepAliveURL))
                {
                    Log.Information("Keep Alive");
                    HttpGet(keepAliveURL); //hack to keep IIS server alive
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error occurred while running JobRetrievalJob:");
            }
        }
        public virtual async Task PlaytestStartingInTask(RconService rconService, SrcdsLogService srcdsLogService,
                                                         AnnouncementMessage announcementMessage)
        {
            if (_dataService.RSettings.ProgramSettings.Debug)
            {
                _ = _log.LogMessage("Base class PlaytestStartingInTask", false, color: LOG_COLOR);
            }

            //Ensure server is awake and RCON connection is established. Run other things while waking server
            _ = rconService.WakeRconServer(ServerLocation);

            //Start asking the server for player counts.
            _dataService.SetIncludePlayerCount(true);
            //Start asking for player counts
            JobManager.AddJob(
                async() => await rconService.GetPlayCountFromServer(ServerLocation),
                s => s.WithName("[QueryPlayerCount]").ToRunEvery(60).Seconds());

            //Figure out how far away from start we are
            string countdownString = null;
            var    countdown       = StartDateTime.GetValueOrDefault().Subtract(DateTime.Now);

            if (StartDateTime.GetValueOrDefault().CompareTo(DateTime.Now) < 0)
            {
                countdownString = $"Started: {countdown:h\'H \'m\'M\'} ago!";
            }
            else
            {
                countdownString = countdown.ToString("d'D 'h'H 'm'M'").TrimStart(' ', 'D', 'H', '0');
            }

            await rconService.RconCommand(ServerLocation, "sv_cheats 0");

            var mentionRole = TesterRole;

            //Handle comp or casual
            if (IsCasual)
            {
                await rconService.RconCommand(ServerLocation,
                                              $"sv_password {_dataService.RSettings.General.CasualPassword}");
            }
            else
            {
                mentionRole = _dataService.CompetitiveTesterRole;
            }

            //Skip the alert.
            if (!_dataService.GetStartAlertStatus())
            {
                _dataService.SetStartAlert(true);
                return;
            }

            var unsubInfo = Game.ToString();

            if (!IsCasual)
            {
                unsubInfo = "comp";
            }

            await TesterRole.ModifyAsync(x => { x.Mentionable = true; });

            await TestingChannel.SendMessageAsync($"Heads up {mentionRole.Mention}! " +
                                                  $"There is a playtest starting in {countdownString}." +
                                                  $"\nType `>playtester {unsubInfo}` to manage {unsubInfo} playtest notifications.",
                                                  embed : announcementMessage.CreatePlaytestEmbed(this, true, AnnouncementMessage.Id));

            await TesterRole.ModifyAsync(x => { x.Mentionable = false; });

            //DM users about their test
            foreach (var creator in Creators)
            {
                try
                {
                    await creator.SendMessageAsync(
                        $"Don't forget that you have a playtest for __**{CleanedTitle}**__ in __**{countdownString}**__");
                }
                catch
                {
                    //Could not DM creator about their test.
                }
            }
        }
예제 #29
0
 public async void ScheduleJobRecurring(string jobID, int intervalSeconds, Action job, int delaySeconds)
 {
     await Task.Delay(TimeSpan.FromSeconds(delaySeconds)).ConfigureAwait(false);
     JobManager.AddJob(job, (x) => x.WithName(jobID).ToRunNow().AndEvery(intervalSeconds).Seconds());
 }
예제 #30
0
        /// <summary>Run all simulations.</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Run(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            this.ErrorMessage = null;

            // Get a reference to the JobManager so that we can add jobs to it.
            jobManager = e.Argument as JobManager;

            // Get a reference to our child DataStore.
            DataStore store = Apsim.Child(this, typeof(DataStore)) as DataStore;

            // Remove old simulation data.
            store.RemoveUnwantedSimulations(this);

            Simulation[] simulationsToRun;
            if (SimulationToRun == null)
            {
                // As we are going to run all simulations, we can delete all tables in the DataStore. This
                // will clean up order of columns in the tables and removed unused ones.
                store.DeleteAllTables();

                store.Disconnect();

                simulationsToRun = Simulations.FindAllSimulationsToRun(this);
            }
            else
                simulationsToRun = Simulations.FindAllSimulationsToRun(SimulationToRun);

            MakeSubstitutions(simulationsToRun);

            NumToRun = simulationsToRun.Length;
            NumCompleted = 0;

            if (NumToRun == 1)
            {
                // Skip running in another thread.
                simulationsToRun[0].Commencing -= OnSimulationCommencing;
                simulationsToRun[0].Commencing += OnSimulationCommencing;
                simulationsToRun[0].Run(null, null);
            }
            else
            {
                foreach (Simulation simulation in simulationsToRun)
                {
                    simulation.Commencing -= OnSimulationCommencing;
                    simulation.Commencing += OnSimulationCommencing;
                    jobManager.AddJob(simulation);
                }
            }
        }
예제 #31
0
        private void SendButtonClick(object sender, RoutedEventArgs e)
        {
            if (toTextBox.Text == string.Empty || themeText.Text == string.Empty)
            {
                MessageBox.Show("Заполните все поля для опрации отправки сообщения!");
                return;
            }

            if (TypeComboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите период отправки сообщений!");
                return;
            }

            if (!TimeSpan.TryParse(startTime.Text, out TimeSpan timeStart))
            {
                MessageBox.Show("Время старта заполнено не корректно!");
                return;
            }

            if (!TimeSpan.TryParse(startTime.Text, out TimeSpan timeEnd))
            {
                MessageBox.Show("Время конца заполнено не корректно!");
                return;
            }

            if (startDate.SelectedDate.Value.AddHours(timeStart.Hours).AddMinutes(timeStart.Minutes) < DateTime.Now)
            {
                MessageBox.Show("Дата старта операции отправки сообщения не должна быть меньше нынешней даты!");
                return;
            }

            if (endDate.SelectedDate.Value.AddHours(timeEnd.Hours).AddMinutes(timeEnd.Minutes) < startDate.SelectedDate.Value.AddHours(timeStart.Hours).AddMinutes(timeStart.Minutes))
            {
                MessageBox.Show("Дата конца операции отправки сообщения не должна быть меньше даты старта!");
                return;
            }

            const int INTERVAL   = 1;
            var       periodType = (Types)TypeComboBox.SelectedValue;

            string jobName = "";

            if (periodType == Types.Day)
            {
                jobName = "DayJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Days().At(timeStart.Hours, timeStart.Minutes));
            }
            else if (periodType == Types.Week)
            {
                jobName = "WeekJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Weeks().On(DayOfWeek.Monday).At(timeStart.Hours, timeStart.Minutes));
            }
            else if (periodType == Types.Month)
            {
                jobName = "MonthJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Months().OnTheFirst(DayOfWeek.Monday).At(timeStart.Hours, timeStart.Minutes));
            }
            else if (periodType == Types.Year)
            {
                jobName = "YearJob";
                JobManager.AddJob(() => Dispatcher.BeginInvoke(new Action(SendEmailAsync), DispatcherPriority.Background), (schedule) => schedule.WithName(jobName).ToRunEvery(INTERVAL).Years().On(1).At(timeStart.Hours, timeStart.Minutes));
            }

            if (startDate.DisplayDate == DateTime.Now.Date)
            {
                JobManager.Start();
            }

            if (endDate.SelectedDate.Value.AddHours(timeEnd.Hours).AddMinutes(timeEnd.Minutes) == DateTime.Now.Date)
            {
                JobManager.Stop();
                JobManager.RemoveJob(jobName);
            }
        }
예제 #32
0
 /// <summary>
 /// Adds a job to the scheduler.
 /// </summary>
 /// <param name="action">The method to call when the time has elapsed.</param>
 /// <param name="schedule">The schedule defining when the job runs.</param>
 public static void AddJob(Action action, Action <Schedule> schedule) => JobManager.AddJob(action, schedule);
예제 #33
0
		public void Should_Call_Dispose()
        {
            JobManager.AddJob<DisposableJob>(s => s.ToRunNow());
            Thread.Sleep(50);
            Assert.IsTrue(DisposableJob.Disposed);
		}
예제 #34
0
        public async Task AddAsync(string type, string date, ISocketMessageChannel reminderChannel, string className, string name, [Remainder] string description)
        {
            if (type.ToLower() != "quiz" && type.ToLower() != "test" && type.ToLower() != "event")
            {
                var error = new EmbedBuilder()
                            .WithTitle("Command Failed :(")
                            .WithDescription(type + " is not a valid type!")
                            .WithFooter("Created by Jai")
                            .WithColor(Color.Red);

                await ReplyAsync("", false, error.Build());

                return;
            }

            DateTimeOffset parsedDate;

            if (DateTimeOffset.TryParse(date, out parsedDate))
            {
                if ((parsedDate - DateTime.Now).Days + 1 >= 5)
                {
                    JobManager.AddJob(
                        () => SendEventMessage(type, parsedDate.Date, reminderChannel, className, name, description),
                        s => s.ToRunOnceAt(parsedDate.Date.AddDays(-5)));
                }
                if ((parsedDate - DateTime.Now).Days + 1 >= 3)
                {
                    JobManager.AddJob(
                        () => SendEventMessage(type, parsedDate.Date, reminderChannel, className, name, description),
                        s => s.ToRunOnceAt(parsedDate.Date.AddDays(-5)));
                }
                if ((parsedDate - DateTime.Now).Days + 1 >= 1)
                {
                    JobManager.AddJob(
                        () => SendEventMessage(type, parsedDate.Date, reminderChannel, className, name, description),
                        s => s.ToRunOnceAt(parsedDate.Date.AddDays(-5)));
                }

                JobManager.AddJob(
                    () => SendEventMessage(type, parsedDate.Date, reminderChannel, className, name, description),
                    s => s.ToRunOnceAt(parsedDate.Date));


                var builder = new EmbedBuilder()
                              .WithTitle(char.ToUpper(type[0]) + type.Substring(1) + " Added")
                              .WithDescription($"{char.ToUpper(type[0]) + type.Substring(1)} added for {className} on {parsedDate}!")
                              .AddField(new EmbedFieldBuilder().WithName(name).WithValue(description))
                              .WithColor(Color.Green)
                              .WithFooter("Created by Jai")
                              .WithAuthor(Context.User);

                await ReplyAsync("", false, builder.Build());
            }
            else
            {
                var error = new EmbedBuilder()
                            .WithTitle("Command Failed :(")
                            .WithDescription("Invalid Date!")
                            .WithFooter("Created by Jai")
                            .WithColor(Color.Red);

                await ReplyAsync("", false, error.Build());
            }
        }
예제 #35
0
 /// <summary>
 ///     Adds a job schedule to the job manager.
 /// </summary>
 /// <param name="job">Job to run.</param>
 /// <param name="schedule">Job schedule to add.</param>
 public void AddJob(Action job, Action <Schedule> schedule)
 {
     JobManager.AddJob(job, schedule);
 }
예제 #36
0
        /// <summary>
        ///     Adds required jobs on startup
        /// </summary>
        public void AddRequiredJobs()
        {
            //Read in the last playtest event from the DB
            _calendar.BootStorePreviousPlaytestEvent();

            _ = _log.LogMessage("Adding required scheduled jobs...", false, color: LOG_COLOR);

            //Ask Google API for new tests every 60 seconds.
            JobManager.AddJob(async() => await _calendar.UpdateTestEventCache(), s => s
                              .WithName("[UpdatePlaytestEventCacheNow]").ToRunNow());

            JobManager.AddJob(async() => await _calendar.UpdateTestEventCache(), s => s
                              .WithName("[UpdatePlaytestEventCache]").ToRunEvery(60).Seconds());

            //Delay the announcement updates so the calendar refreshes first.
            Task.Run(() =>
            {
                Thread.Sleep(10000);
                //Add schedule for playtest information
                JobManager.AddJob(async() => await _playtestService.PostOrUpdateAnnouncement("csgo"), s => s
                                  .WithName("[PostOrUpdateAnnouncement_CSGO]").ToRunEvery(60).Seconds());


                JobManager.AddJob(async() => await _playtestService.PostOrUpdateAnnouncement("tf2"), s => s
                                  .WithName("[PostOrUpdateAnnouncement_TF2]").ToRunEvery(60).Seconds());
            });

            //Early refresh on playtest announcements.
            JobManager.AddJob(async() => await _playtestService.PostOrUpdateAnnouncement("csgo"), s => s
                              .WithName("[PostOrUpdateAnnouncementNow_CSGO]").ToRunOnceIn(15).Seconds());

            JobManager.AddJob(async() => await _playtestService.PostOrUpdateAnnouncement("tf2"), s => s
                              .WithName("[PostOrUpdateAnnouncementNow_TF2]").ToRunOnceIn(15).Seconds());

            //Reattach to the old announcement message quickly
            JobManager.AddJob(async() => await _playtestService.TryAttachPreviousAnnounceMessage(), s => s
                              .WithName("[TryAttachPreviousAnnounceMessage]").ToRunOnceIn(5).Seconds());

            //On start up schedule of playtest announcements
            JobManager.AddJob(() => _playtestService.ScheduleAllPlaytestAnnouncements(), s => s
                              .WithName("[SchedulePlaytestAnnouncementsBoot]").ToRunOnceIn(10).Seconds());

            //Add schedule for playing information
            JobManager.AddJob(async() => await UpdatePlaying(), s => s
                              .WithName("[PlayingUpdate]").ToRunEvery(20).Seconds());

            //Add schedule for playtest count update, will do every few hours, and now to seed the value.
            JobManager.AddJob(UpdatePlayTestCount, s => s
                              .WithName("[PlaytestCountUpdate]").ToRunEvery(2).Hours());
            JobManager.AddJob(UpdatePlayTestCount, s => s
                              .WithName("[PlaytestCountUpdateNow]").ToRunNow());

            //Update playerbase
            JobManager.AddJob(async() => await UpdatePlayerbase(), s => s
                              .WithName("[PlayerbaseUpdate]").ToRunEvery(1).Days().At(0, 00));

            //Daily Faceit Demo Fetching
            JobManager.AddJob(async() => await DailyDemoRequests(), s => s
                              .WithName("[FaceitDemoRequest]").ToRunEvery(1).Days().At(0, 00));

            //Re-add joined users so they get welcome message and playtester role.
            //This would only happen if the bot restarts after someone joins, but didn't get the welcome message.
            foreach (var user in DatabaseUtil.GetAllUserJoins())
            {
                try
                {
                    //Test getting user in a try catch, if we can't they left the server.
                    var validUser = _dataService.Guild.GetUser(user.UserId);

                    //Send welcome message right away, or wait?
                    if (DateTime.Now > user.JoinTime.AddMinutes(10))
                    {
                        //Timer expired, schedule now
                        JobManager.AddJob(async() => await _userHandler.UserWelcomeMessage(validUser), s => s
                                          .WithName($"[UserJoin_{validUser.Id}]").ToRunOnceIn(10).Seconds());
                    }
                    else
                    {
                        //Not passed, scheduled ahead
                        JobManager.AddJob(async() => await _userHandler.UserWelcomeMessage(validUser), s => s
                                          .WithName($"[UserJoin_{validUser.Id}]").ToRunOnceAt(user.JoinTime.AddMinutes(10)));
                    }
                }
                catch
                {
                    //If we cannot get a user, that means that user left the server. So remove them.
                    if (_dataService.RSettings.ProgramSettings.Debug)
                    {
                        _ = _log.LogMessage($"Cannot re-add user join for ID {user.UserId}" +
                                            "because they left the server.", false, color: LOG_COLOR);
                    }

                    DatabaseUtil.RemoveJoinedUser(user.UserId);
                }
            }

            //Re-add user mutes
            foreach (var user in DatabaseUtil.GetAllActiveUserMutes())
            {
                //Send welcome message right away, or wait?
                if (DateTime.Now > user.MuteTime.AddMinutes(user.Duration))
                {
                    //Timer expired, schedule now
                    JobManager.AddJob(async() => await _dataService.UnmuteUser(user.UserId), s => s
                                      .WithName($"[UnmuteUser_{user.UserId}]").ToRunOnceIn(20).Seconds());
                }
                else
                {
                    //Not passed, scheduled ahead
                    JobManager.AddJob(async() => await _dataService.UnmuteUser(user.UserId), s => s
                                      .WithName($"[UnmuteUser_{user.UserId}]").ToRunOnceAt(user.MuteTime.AddMinutes(user.Duration)));
                }
            }

            //Re-add server reservations.
            foreach (var reservation in DatabaseUtil.GetAllServerReservation())
            {
                string mention = null;

                try
                {
                    mention = _dataService.Guild.GetUser(reservation.UserId).Mention;
                }
                catch
                {
                    //Can't get user don't do a mention
                }

                //Send welcome message right away, or wait?
                if (DateTime.Now > reservation.StartTime.AddHours(3))
                {
                    //Timer expired, schedule now
                    JobManager.AddJob(async() => await _dataService.BotChannel.SendMessageAsync($"{mention}",
                                                                                                embed: _reservationService.ReleaseServer(reservation.UserId,
                                                                                                                                         "The reservation has expired.", _dataService.BotChannel)),
                                      s => s.WithName(
                                          $"[TSRelease_{GeneralUtil.GetServerCode(reservation.ServerId)}_{reservation.UserId}]")
                                      .ToRunOnceIn(15).Seconds());
                }
                else
                {
                    //Not passed, scheduled ahead
                    JobManager.AddJob(async() => await _dataService.BotChannel.SendMessageAsync($"{mention}",
                                                                                                embed: _reservationService.ReleaseServer(reservation.UserId,
                                                                                                                                         "The reservation has expired.", _dataService.BotChannel)),
                                      s => s.WithName(
                                          $"[TSRelease_{GeneralUtil.GetServerCode(reservation.ServerId)}_{reservation.UserId}]")
                                      .ToRunOnceAt(reservation.StartTime.AddHours(3)));
                }
            }

            DisplayScheduledJobs();
        }