Ejemplo n.º 1
0
        /// <summary>
        /// 删除指定的任务
        /// </summary>
        /// <param name="jobName">任务名称</param>
        /// <param name="jobGroup">任务组</param>
        /// <returns></returns>
        public async Task <ScheduleResult> DeleteJobAsync(string jobName, string jobGroup)
        {
            ScheduleResult result = new ScheduleResult();

            try
            {
                JobKey jobKey = new JobKey(jobName, jobGroup);

                if (await Scheduler.CheckExists(jobKey))
                {
                    //先暂停,再移除
                    await Scheduler.PauseJob(jobKey);

                    await Scheduler.DeleteJob(jobKey);
                }
                else
                {
                    result.ResultCode = -1;
                    result.ResultMsg  = "任务不存在";
                }
            }
            catch (Exception ex)
            {
                _logger.Error(nameof(AddJobAsync), ex, null);
                result.ResultCode = -4;
                result.ResultMsg  = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 暂停指定任务计划
        /// </summary>
        /// <param name="jobName">任务名</param>
        /// <param name="jobGroup">任务分组</param>
        /// <returns></returns>
        public async Task <ScheduleResult> StopJobAsync(string jobName, string jobGroup)
        {
            ScheduleResult result = new ScheduleResult();

            try
            {
                JobKey jobKey = new JobKey(jobName, jobGroup);
                scheduler = await GetSchedulerAsync();

                if (await scheduler.CheckExists(jobKey))
                {
                    await scheduler.PauseJob(new JobKey(jobName, jobGroup));
                }
                else
                {
                    result.Code    = -1;
                    result.Message = "任务不存在";
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
                result.Code    = -4;
                result.Message = ex.ToString();
            }
            return(result);//出现异常
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Starts the actual solvers, returns the best schedule when all solvers are done.
        /// </summary>
        /// <returns>The best schedule when all solvers are done</returns>
        private ScheduleResult Solve()
        {
            // Initialize all variables:
            Task[] tasks = new Task[ThreadCount];
            stati             = new SolverStatus[ThreadCount];
            iterationCounters = new int[ThreadCount];
            bestResults       = new ScheduleResult[ThreadCount];
            for (int i = 0; i < ThreadCount; i -= -1)
            {
                bestResults[i] = new ScheduleResult()
                {
                    Score = double.MaxValue
                }
            }
            ;

            // Start the statusupdater and leaderboard:
            Task statusUpdater = Task.Factory.StartNew(() => StatusUpdater());

            // Start the solvers:
            for (int i = 0; i < ThreadCount; i++)
            {
                int index = i;
                tasks[index] = Task.Factory.StartNew(() => SolveOne(index, ref bestResults[index]));
            }
            // Wait untill all solvers are done:
            Task.WaitAll(tasks);
            // Stop the statusupdater:
            stopStatusUpdater = true;
            statusUpdater.Wait();
            // Return the best schedule:
            return(best);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 恢复指定的任务计划,如果是程序奔溃后 或者是进程杀死后的恢复,此方法无效
        /// </summary>
        /// <param name="jobName">任务名称</param>
        /// <param name="jobGroup">任务组</param>
        /// <returns></returns>
        public async Task <ScheduleResult> ResumeJobAsync(string jobName, string jobGroup)
        {
            ScheduleResult result = new ScheduleResult();

            try
            {
                JobKey jobKey = new JobKey(jobName, jobGroup);

                if (await Scheduler.CheckExists(jobKey))
                {
                    //resumejob 恢复
                    await Scheduler.PauseJob(jobKey);

                    await Scheduler.ResumeJob(jobKey);
                }
                else
                {
                    result.ResultCode = -1;
                    result.ResultMsg  = "任务不存在";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, nameof(ResumeJobAsync));

                result.ResultCode = -4;
                result.ResultMsg  = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 5
0
        public async Task <ScheduleResult> ResumeJobAsync(string jobName, string jobGroup)
        {
            ScheduleResult scheduleResult = new ScheduleResult();

            try
            {
                var jobKey = new JobKey(jobName, jobGroup);
                if (await Scheduler.CheckExists(jobKey))
                {
                    await Scheduler.PauseJob(jobKey);

                    await Scheduler.ResumeJob(jobKey);
                }
                else
                {
                    scheduleResult.ResultCode = -1;
                    scheduleResult.ResultMsg  = "任务不存在";
                }
            }
            catch (Exception ex)
            {
                _logger.Error(nameof(AddJobAsync), ex, null);

                scheduleResult.ResultCode = -4;
                scheduleResult.ResultMsg  = ex.ToString();
            }
            return(scheduleResult);
        }
Ejemplo n.º 6
0
 public void Variable_Initialize(ScheduleResult script_S)
 {
     if (script_S != null)
     {
         script_Schedule = script_S;
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// 删除指定的任务
        /// </summary>
        /// <param name="jobName">任务名称</param>
        /// <param name="jobGroup">任务组</param>
        /// <returns></returns>
        public async Task <ScheduleResult> DeleteJobAsync(string jobName, string jobGroup)
        {
            ScheduleResult result = new ScheduleResult();

            try
            {
                JobKey jobKey = new JobKey(jobName, jobGroup);

                if (await Scheduler.CheckExists(jobKey))
                {
                    //先暂停,再移除
                    await Scheduler.PauseJob(jobKey);

                    await Scheduler.DeleteJob(jobKey);
                }
                else
                {
                    result.Code    = -1;
                    result.Message = "任务不存在";
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
                result.Code    = -4;
                result.Message = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 8
0
        public async Task <ScheduleResult> Get(Guid id)
        {
            var customer = await scheduleReadOnlyRepository.Get(id);

            ScheduleResult scheduleResult = resultConverter.Map <ScheduleResult>(customer);

            return(scheduleResult);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Constructor, initializes some variables.
 /// </summary>
 /// <param name="orders"></param>
 public Solver(List <Order> orders)
 {
     best = new ScheduleResult()
     {
         Score = double.MaxValue
     };
     this.orders = orders;
 }
Ejemplo n.º 10
0
        public void TestInitialize()
        {
            this.timeService   = Mock.Of <ITimeService>();
            this.schedueResult = new ScheduleResult();

            var dataProvider = Mock.Of <IScheduleDataProvider>(s => s.GetSchedules() == this.schedueResult);

            this.factory = new MeetingSchedulerFactory(this.timeService, dataProvider);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 添加调度任务
        /// </summary>
        /// <param name="JobName">任务名称</param>
        /// <param name="JobGroup">任务分组</param>
        /// <param name="JobNamespaceAndClassName">任务完全限定名</param>
        /// <param name="JobAssemblyName">任务程序集名称</param>
        /// <param name="CronExpress">Cron表达式</param>
        /// <param name="StarTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public async Task <ScheduleResult> AddJobAsync(String JobName, String JobGroup, String JobNamespaceAndClassName, String JobAssemblyName, string CronExpress)
        {
            ScheduleResult result = new ScheduleResult();

            try
            {
                if (string.IsNullOrEmpty(JobName) || string.IsNullOrEmpty(JobGroup) || string.IsNullOrEmpty(JobNamespaceAndClassName) || string.IsNullOrEmpty(JobAssemblyName) || string.IsNullOrEmpty(CronExpress))
                {
                    result.ResultCode = -3;
                    result.ResultMsg  = $"参数不能为空";
                    return(result);//出现异常
                }
                var            starRunTime = DateTime.Now;
                var            EndTime     = DateTime.MaxValue.AddDays(-1);
                DateTimeOffset endRunTime  = DateBuilder.NextGivenSecondDate(EndTime, 1);
                JobKey         jobKey      = new JobKey(JobName, JobGroup);
                if (await Scheduler.CheckExists(jobKey))
                {
                    await Scheduler.PauseJob(jobKey);

                    await Scheduler.DeleteJob(jobKey);
                }
                Assembly assembly = Assembly.LoadFile(JobAssemblyName);
                Type     jobType  = assembly.GetType(JobNamespaceAndClassName);
                //var jobType = Type.GetType(JobNamespaceAndClassName + "," + JobAssemblyName);
                if (jobType == null)
                {
                    result.ResultCode = -1;
                    result.ResultMsg  = "系统找不到对应的任务,请重新设置";
                    return(result);//出现异常
                }
                IJobDetail job = JobBuilder.Create(jobType)
                                 .WithIdentity(jobKey).UsingJobData("ServerName", Scheduler.SchedulerName)
                                 .Build();
                ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                       .StartAt(starRunTime)
                                       .EndAt(endRunTime)
                                       .WithIdentity(JobName, JobGroup)
                                       .WithCronSchedule(CronExpress)
                                       .Build();
                await Scheduler.ScheduleJob(job, trigger);

                if (!Scheduler.IsStarted)
                {
                    await Scheduler.Start();
                }
                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, nameof(AddJobAsync));
                result.ResultCode = -4;
                result.ResultMsg  = ex.ToString();
                return(result);//出现异常
            }
        }
Ejemplo n.º 12
0
        public void TestInitialize()
        {
            this.currentDate    = new DateTime(2018, 01, 01);
            this.scheduleResult = new ScheduleResult();

            var timeService = Mock.Of <ITimeService>(s => s.CurrentDate == this.currentDate);

            this.scheduler = new MeetingScheduler(timeService
                                                  , null);
        }
Ejemplo n.º 13
0
        public ScheduleResult deleteSchedule(string schedule_id)
        {
            Preconditions.checkArgument(schedule_id != null, (object)"schedule_id should not be empty");
            Console.WriteLine(schedule_id);
            ResponseWrapper responseWrapper = this.sendDelete("https://api.jpush.cn" + "/v3/schedules" + "/" + schedule_id, this.Authorization(), schedule_id);
            ScheduleResult  scheduleResult  = new ScheduleResult();

            scheduleResult.ResponseResult = responseWrapper;
            ScheduleSuccess scheduleSuccess = (ScheduleSuccess)JsonConvert.DeserializeObject <ScheduleSuccess>(responseWrapper.responseContent);

            return(scheduleResult);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Prints the best solver result.
 /// </summary>
 /// <param name="best">The best schedule result</param>
 /// <param name="writeToFile">if true saves the best result as string ready to put in the checker</param>
 /// <param name="fileName">filename of the file in which the best result is saved, ignored if writeToFile=false</param>
 private static void PrintResult(ScheduleResult best, bool writeToFile = true, string fileName = "result")
 {
     Console.Clear();
     Console.WriteLine("===============" +
                       "\n= BEST RESULT =" +
                       "\n===============");
     Console.WriteLine(best.Stats);
     if (writeToFile)
     {
         File.WriteAllText($@".\{fileName}.txt", best.Check.ToString());
     }
     Console.WriteLine("===============");
 }
Ejemplo n.º 15
0
        //执行结果解析
        public static string transResult(ScheduleResult result)
        {
            string str = string.Empty;

            switch (result)
            {
            case ScheduleResult.UnExecute: str = Model_Data.Language.ScheduleStr.AwaitingExecution; break;

            case ScheduleResult.Outdate: str = Model_Data.Language.ScheduleStr.Failure; break;

            case ScheduleResult.Success: str = Model_Data.Language.ScheduleStr.success; break;
            }
            return(str);
        }
Ejemplo n.º 16
0
        public async Task <ScheduleResult> Process(UpdateScheduleCommand command)
        {
            Domain.Schedule.Schedule schedule = new Domain.Schedule.Schedule(command.ScheduleId, command.Day, command.Hour)
            {
                Customer = await customerReadOnlyRepository.Get(command.CustomerId),
                Service  = await serviceReadOnlyRepository.Get(command.ServiceId)
            };

            await scheduleWriteOnlyRepository.Update(schedule);

            ScheduleResult scheduleResult = resultConverter.Map <ScheduleResult>(schedule);

            return(scheduleResult);
        }
Ejemplo n.º 17
0
        public ScheduleResult sendSchedule(string schedulepayload)
        {
            Preconditions.checkArgument(!string.IsNullOrEmpty(schedulepayload), (object)"schedulepayload should not be empty");
            Console.WriteLine(schedulepayload);
            ResponseWrapper responseWrapper = this.sendPost("https://api.jpush.cn" + "/v3/schedules", this.Authorization(), schedulepayload);
            ScheduleResult  scheduleResult  = new ScheduleResult();

            scheduleResult.ResponseResult = responseWrapper;
            ScheduleSuccess scheduleSuccess = (ScheduleSuccess)JsonConvert.DeserializeObject <ScheduleSuccess>(responseWrapper.responseContent);

            scheduleResult.schedule_id = scheduleSuccess.schedule_id;
            scheduleResult.name        = scheduleSuccess.name;
            return(scheduleResult);
        }
Ejemplo n.º 18
0
        public void TestInitialize()
        {
            this.currentDate    = new DateTime(2018, 01, 01);
            this.scheduleResult = new ScheduleResult();

            var timeService = Mock.Of <ITimeService>(s => s.CurrentDate == this.currentDate);

            var meetingSchedulerCalculator = Mock.Of <IMeetingSchedulerCalculator>(s => s.GetAvailableMeetings(It.IsAny <int>()
                                                                                                               , It.IsAny <ISet <Guid> >()
                                                                                                               , this.currentDate) == Enumerable.Empty <MeetingSchedulerResult>());

            this.scheduler = new MeetingScheduler(timeService
                                                  , meetingSchedulerCalculator);
        }
Ejemplo n.º 19
0
        public override PayrollResult Evaluate(PayrollPeriod period, PayTagGateway tagConfig, IDictionary <TagRefer, PayrollResult> results)
        {
            ScheduleResult scheduleWorkResult = (ScheduleResult)GetResultBy(results, TAG_SCHEDULE_WORK);

            int[] weekHours = scheduleWorkResult.WeekSchedule;

            int[] hoursCalendar = ComputeResultValue(period, weekHours);

            var resultValues = new Dictionary <string, object>()
            {
                { "month_schedule", hoursCalendar }
            };

            return(new TimesheetResult(TagCode, Code, this, resultValues));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Starts the solver.
        /// Awaits until either:
        /// - All solver instances are finished.
        /// - Userinterrupt.
        /// Then prints the best result.
        /// </summary>
        private static void AwaitAndPrintResults()
        {
            Task userInterruptAwaiter = Task.Factory.StartNew(() => AwaitUserInterrupt(solver));

            results.Wait();
            if (!userInterruptAwaiter.IsCompleted)
            {
                solverStillGoing = false;
            }
            userInterruptAwaiter.Wait();
            ScheduleResult res = results.Result;

            Console.Beep();
            PrintResult(res);
        }
        public void ShouldBeAbleToGetSchedule()
        {
            const string url  = "My URL";
            const string json = "JSON";

            var scheduleResult = new ScheduleResult();

            this.urlProvider.Setup(s => s.GetUrl()).Returns(url);
            this.jsonRepository.Setup(s => s.Get(url)).Returns(json);
            this.jsonParser.Setup(s => s.ToObject <RootObject>(json)).Returns(new RootObject {
                ScheduleResult = scheduleResult
            });

            var result = this.dataProvider.GetSchedules();

            Assert.AreSame(scheduleResult, result);
        }
Ejemplo n.º 22
0
        public ScheduleResult sendSchedule(string schedulepayload)
        {
            Preconditions.checkArgument(!string.IsNullOrEmpty(schedulepayload), "schedulepayload should not be empty");
            Console.WriteLine(schedulepayload);
            String url = HOST_NAME_SSL;

            url += PUSH_PATH;
            ResponseWrapper result     = sendPost(url, Authorization(), schedulepayload);
            ScheduleResult  messResult = new ScheduleResult();

            messResult.ResponseResult = result;

            ScheduleSuccess scheduleSuccess = JsonConvert.DeserializeObject <ScheduleSuccess>(result.responseContent);

            messResult.schedule_id = scheduleSuccess.schedule_id;
            messResult.name        = scheduleSuccess.name;
            return(messResult);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 直接使用 BookAppService.UpdateAsync 来更新实体
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> OnPostAsync()
        {
            var jobInfoDto = await _jobInfoAppService.GetAsync(Id);

            ScheduleResult result = new ScheduleResult();

            if (jobInfoDto.JobStatus != JobInfo.JobStatus)
            {
                if (jobInfoDto.JobStatus == JobStatu.Deleted)
                {
                    //如果之前的状态是已删除的话,先创建任务再进行操作
                    await _scheduleCenter.AddJobAsync(JobInfo.JobName,
                                                      JobInfo.JobGroup,
                                                      JobInfo.JobNamespace + "." + JobInfo.JobClassName,
                                                      JobInfo.JobAssemblyName,
                                                      JobInfo.CronExpress,
                                                      JobInfo.StarTime,
                                                      JobInfo.EndTime);
                }
                if (JobInfo.JobStatus == JobStatu.Deleted)
                {
                    result = await _scheduleCenter.DeleteJobAsync(JobInfo.JobName, JobInfo.JobGroup);

                    if (result.Code == 0)
                    {
                        await _jobInfoAppService.DeleteAsync(Id);
                    }
                    return(NoContent());
                }
                else if (JobInfo.JobStatus == JobStatu.Running)
                {
                    result = await _scheduleCenter.ResumeJobAsync(JobInfo.JobName, JobInfo.JobGroup);
                }
                else
                {
                    result = await _scheduleCenter.StopJobAsync(JobInfo.JobName, JobInfo.JobGroup);
                }
            }
            if (result.Code == 0)
            {
                await _jobInfoAppService.UpdateAsync(Id, JobInfo);
            }
            return(NoContent());
        }
        public void TestInitialize()
        {
            var jsonParser     = new JsonParser();
            var jsonRepository = new JsonRepository();
            var urlProvider    = new RESTfulURLProvider();

            var dataProvider = new ScheduleDataProvider(jsonParser
                                                        , jsonRepository
                                                        , urlProvider
                                                        );

            this.scheduleResult = dataProvider.GetSchedules();

            var calculator = new MeetingSchedulerCalculator(this.scheduleResult);

            this.timeService = new Mock <ITimeService>();

            this.scheduler = new MeetingScheduler(this.timeService.Object
                                                  , calculator);
        }
Ejemplo n.º 25
0
        //DELETE https://api.jpush.cn/v3/schedules/{schedule_id}
        //删除指定的Schedule任务
        public ScheduleResult deleteSchedule(string schedule_id)
        {
            Preconditions.checkArgument(schedule_id != null, "schedule_id should not be empty");
            Console.WriteLine(schedule_id);
            String url = HOST_NAME_SSL;

            url += PUSH_PATH;
            url += DELETE_PATH;
            url += schedule_id;
            ResponseWrapper result     = sendDelete(url, Authorization(), schedule_id);
            ScheduleResult  messResult = new ScheduleResult();

            messResult.ResponseResult = result;

            ScheduleSuccess scheduleSuccess = JsonConvert.DeserializeObject <ScheduleSuccess>(result.responseContent);

            //messResult.schedule_id = scheduleSuccess.schedule_id;
            //messResult.name = scheduleSuccess.name;

            return(messResult);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Writes the successfully scheduled recordings to an output CSV file.
        /// </summary>
        /// <param name="sessionMgr">The client in which holds the information about the sessions.</param>
        /// <param name="sessionAuth">The authentication information for which to access the information from <paramref name="sessionMgr"/>.</param>
        /// <param name="scheduleSuccesses">The list of unique identifiers for each successfully scheduled recording.</param>
        /// <param name="sender">The BackgroundWorker to make this method asynchronous.</param>
        public static void WriteSuccessFile(ISessionManagement sessionMgr,
                                            Utilities.SessionManagement46.AuthenticationInfo sessionAuth,
                                            List <Guid> scheduleSuccesses,
                                            BackgroundWorker sender)
        {
            // Get the information for each scheduled session and put it into a ScheduleResult object.
            List <ScheduleResult> scheduled = new List <ScheduleResult>();

            Session[] session = sessionMgr.GetSessionsById(sessionAuth, scheduleSuccesses.ToArray());
            for (int j = 0; j < session.Length; j++)
            {
                if (sender != null)
                {
                    // NOTE: This method runs so quickly even at many lines, that this progress report may not be necessary
                    // to update the UI. Still good to have in the event this stalls here though.
                    sender.ReportProgress(j);
                }
                // Use 0 for RemoteRecorderIds since currently only dealing with 1 remote recorder.
                ScheduleResult sr = new ScheduleResult(session[j].RemoteRecorderIds[0],
                                                       session[j].FolderId,
                                                       session[j].Id,
                                                       session[j].Name,
                                                       session[j].StartTime?.ToLocalTime(),
                                                       (session[j].StartTime + TimeSpan.FromSeconds(session[j].Duration.GetValueOrDefault()))?.ToLocalTime());
                scheduled.Add(sr);
            }
            // write what was successfully scheduled to output.csv
            // output.csv will only have a header if there were no session scheduled.
            using (TextWriter writer = new StreamWriter(Properties.Settings.Default.LogsLocation + DateTime.Now.ToString("yyyyMMdd_HHmmss") + @"_success_output.csv"))
            {
                if (sender != null)
                {
                    sender.ReportProgress(session.Length);
                }
                var csv = new CsvWriter(writer);
                csv.WriteRecords(scheduled);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the best schedule on a fixed interval
        /// if STATUS is defined:
        /// Prints the status of each solver thread together with
        /// - the current runtime.
        /// - the best score so far.
        /// This is updated each refreshTime miliseconds.
        /// </summary>
        /// <param name="threads">Amount of solvertasks started</param>
        /// <param name="refreshTime">Refresh delay (in miliseconds)</param>
        private void StatusUpdater()
        {
            Console.Clear();
            Stopwatch watch         = Stopwatch.StartNew();
            int       currBestIndex = -1;

            while (!(stopStatusUpdater || UserInterrupt))
            {
                for (int i = 0; i < ThreadCount; i++)
                {
                    ScheduleResult curr = bestResults[i];
                    if (curr.Score < best.Score)
                    {
                        currBestIndex = i;
                        best          = curr;
                    }
                    if (ShowStatus)
                    {
                        SolverStatus stat = stati[i];
                        string       extraInfo;
                        switch (stat)
                        { // In order of most time on status:
                        case SolverStatus.Doing_All:
                            extraInfo = $", iteration: {iterationCounters[i]}";
                            break;

                        case SolverStatus.Done:
                            extraInfo = $", best: {bestResults[i].Score}";
                            break;

                        case SolverStatus.Doing_Add:
                            extraInfo = $", iteration: {iterationCounters[i]}";
                            break;

                        default: extraInfo = ""; break;
                        }
                        Console.SetCursorPosition(0, i);
                        Console.WriteLine($"Task {i}: {stat}{extraInfo}");
                    }
                }

                if (ShowStatus)
                {
                    Console.SetCursorPosition(0, ThreadCount);
                    Console.WriteLine($"===\nBest result produced on task {currBestIndex}:\n{best.String}");
                    Console.WriteLine($"===\nCurrent runtime: {watch.Elapsed}");
                }

                Thread.Sleep(ConsoleUpdateInterval);
            }

            //Timer updater = new Timer(ConsoleUpdateInterval);
            //updater.Elapsed += Updater_Elapsed;
            //updater.Start();
            //void Updater_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            //{
            //    if (stopStatusUpdater || UserInterrupt) updater.Stop();

            //    for (int i = 0; i < ThreadCount; i++)
            //    {
            //        ScheduleResult curr = bestResults[i];
            //        if (curr.Score < best.Score)
            //        {
            //            currBestIndex = i;
            //            best = curr;
            //        }
            //        if (ShowStatus)
            //        {
            //            SolverStatus stat = stati[i];
            //            string extraInfo;
            //            switch (stat)
            //            { // In order of most time on status:
            //                case SolverStatus.Doing_All:
            //                    extraInfo = $", iteration: {iterationCounters[i]}";
            //                    break;
            //                case SolverStatus.Done:
            //                    extraInfo = $", best: {bestResults[i].Score}";
            //                    break;
            //                case SolverStatus.Doing_Add:
            //                    extraInfo = $", iteration: {iterationCounters[i]}";
            //                    break;
            //                default: extraInfo = ""; break;
            //            }
            //            Console.SetCursorPosition(0, i);
            //            Console.WriteLine($"Task {i}: {stat}{extraInfo}");
            //        }
            //    }

            //    if (ShowStatus)
            //    {
            //        Console.SetCursorPosition(0, ThreadCount);
            //        Console.WriteLine($"===\nBest result produced on task {currBestIndex}:\n{best.String}");
            //        Console.WriteLine($"===\nCurrent runtime: {watch.Elapsed}");
            //    }
            //}
            //// Block while the updater is active:
            //while (updater.Enabled) ;
        }
 public MeetingSchedulerCalculator(ScheduleResult scheduleResult)
 {
     this.ScheduleResult = scheduleResult;
 }
Ejemplo n.º 29
0
        void Run(SystemInfo[] systems, SystemType type, double time, int laneCount)
        {
            int            typeCount    = 0;
            double         averageTime  = 0;
            PrecisionTimer processTimer = new PrecisionTimer();
            PrecisionTimer unitTimer    = new PrecisionTimer();

            Console.WriteLine("Test 1 - Adding All Systems at Once");

            for (int i = 0; i < systems.Length; i++)
            {
                if (systems[i].Type == type)
                {
                    typeCount++;
                }
            }

            SafeSystemSchedule schedule = new SafeSystemSchedule(SystemType.Logic, laneCount, typeCount);

            processTimer.Start();
            for (int i = 0; i < systems.Length; i++)
            {
                unitTimer.Start();
                SystemInfo sysInf = systems[i];
                if (!sysInf.Active || sysInf.Type != type)
                {
                    unitTimer.Stop();
                    averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1);
                    unitTimer.Reset();
                    continue;
                }
                schedule.Add(sysInf);
                unitTimer.Stop();
                processTimer.Stop();
                averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1);
                unitTimer.Reset();
                processTimer.Start();
            }
            processTimer.Stop();

            Console.WriteLine("Total Time to Register : " + processTimer.ElapsedSeconds);
            Console.WriteLine("Average Time to Register : " + averageTime);
            Console.WriteLine("Extrapolated Time to Register : " + (averageTime * systems.Length));
            Console.WriteLine("Extrapolated Time without nonTypes : " + (averageTime * typeCount));
            processTimer.Reset();

            Console.ReadLine();

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Test 2 - Adding Each System One at a Time");

            averageTime = 0;
            schedule.Clear();
            processTimer.Start();
            for (int i = 0; i < systems.Length; i++)
            {
                unitTimer.Start();
                SystemInfo sysInf = systems[i];
                if (!sysInf.Active || sysInf.Type != type)
                {
                    unitTimer.Stop();
                    averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1);
                    unitTimer.Reset();
                    continue;
                }
                schedule.Add(sysInf);
                unitTimer.Stop();
                processTimer.Stop();
                averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1);
                unitTimer.Reset();

                while (schedule.NextSystem(0, out SystemInfo sysInfo) != ScheduleResult.Finished)
                {
                    sysInfo.Age = 1;
                }

                processTimer.Start();
            }
            processTimer.Stop();

            Console.WriteLine("Total Time to Register : " + processTimer.ElapsedSeconds);
            Console.WriteLine("Average Time to Register : " + averageTime);
            Console.WriteLine("Extrapolated Time to Register : " + (averageTime * systems.Length));
            Console.WriteLine("Extrapolated Time without nonTypes : " + (averageTime * typeCount));
            processTimer.Reset();

            Console.ReadLine();

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Test 3 - Clear List and Readd");

            SafeSystemSchedule copy = new SafeSystemSchedule(schedule);

            foreach (SystemInfo sysinf in systems)
            {
                SystemUpdate(sysinf);
            }

            processTimer.Start();
            schedule.Clear();

            for (int i = 0; i < systems.Length; i++)
            {
                SystemInfo sysInf = systems[i];
                if (!sysInf.Active || sysInf.Type != type)
                {
                    continue;
                }
                schedule.Add(sysInf);
            }
            processTimer.Stop();

            while (schedule.NextSystem(0, out SystemInfo sysInfo) != ScheduleResult.Finished)
            {
                Console.WriteLine(sysInfo);
            }

            Console.WriteLine("Total Time to clear then readd : " + processTimer.ElapsedSeconds);

            Console.ReadLine();

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Test 4 - Remove Individually and Register One at a time");

            processTimer.Start();

            copy.Reset();

            for (int i = 0; i < systems.Length; i++)
            {
                SystemInfo sysInf = systems[i];
                if (!sysInf.Active || sysInf.Type != type)
                {
                    continue;
                }
                copy.Remove(sysInf);
                copy.Add(sysInf);
            }
            processTimer.Stop();

            while (copy.NextSystem(0, out SystemInfo sysInfo) != ScheduleResult.Finished)
            {
                Console.WriteLine(sysInfo);
            }

            Console.WriteLine("Total Time to remove then readd : " + processTimer.ElapsedSeconds);

            Console.ReadLine();

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Test 5 - System Run");

            schedule.Clear();

            for (int i = 0; i < systems.Length; i++)
            {
                SystemInfo sysInf = systems[i];
                if (!sysInf.Active || sysInf.Type != type)
                {
                    continue;
                }
                schedule.Add(sysInf);
            }

            double currentTime = 0;
            int    finishCount = 0;

            double[] endTimes = new double[laneCount];
            bool[]   finished = new bool[laneCount];
            averageTime = 0;

            processTimer.Start();
            while (!schedule.Finished && currentTime < time && finishCount < laneCount)
            {
                for (int i = 0; i < laneCount; i++)
                {
                    if (endTimes[i] <= currentTime && !finished[i])
                    {
                        unitTimer.Start();
                        schedule.FinishLane(i);
                        ScheduleResult result = schedule.NextSystem(i, out SystemInfo sysInf);

                        if (result == ScheduleResult.Supplied)
                        {
                            sysInf.Age = 0;
                            if (sysInf.AverageRunTime + currentTime > time)
                            {
                                finished[i] = true;
                                finishCount++;
                                unitTimer.Stop();
                                continue;
                            }
                            endTimes[i] = currentTime + sysInf.AverageRunTime;
                        }
                        else if (result == ScheduleResult.Finished)
                        {
                            finished[i] = true;
                            finishCount++;
                        }
                        unitTimer.Stop();
                        processTimer.Stop();
                        averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1);
                        unitTimer.Reset();
                        processTimer.Start();
                    }
                }

                processTimer.Stop();
                double nextTime = double.PositiveInfinity;
                for (int i = 0; i < laneCount; i++)
                {
                    if (endTimes[i] > currentTime && endTimes[i] < nextTime)
                    {
                        nextTime = endTimes[i];
                    }
                }
                if (nextTime != double.PositiveInfinity)
                {
                    currentTime = nextTime;
                }
                processTimer.Start();
            }
            processTimer.Stop();

            Console.WriteLine("Total Time to decide : " + processTimer.ElapsedSeconds);
            Console.WriteLine("Average Time to decide : " + averageTime);
            Console.WriteLine("Extrapolated Time to decide : " + (averageTime * typeCount));
            Console.WriteLine("Total Time Used : " + (currentTime) + "/" + time);
            processTimer.Reset();

            Console.ReadLine();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Main method for each solver task.
        /// In each iteration it generates opCount neighbors using the following operators:
        /// - Add
        /// - Delete
        /// - Transfer
        /// - Swap
        /// (for explanations see the Schedule class)
        /// Then it uses a LocalSolver to pick the next state from the neighbors,
        /// since each local solving algorithm uses a different method to determine the next state.
        /// </summary>
        /// <param name="taskID">The id of the task, used as index for the arrays</param>
        /// <param name="best">The best schedule of this solver task</param>
        private void SolveOne(int taskID, ref ScheduleResult best)
        {
            // Initialize variables
            Schedule start = new Schedule(orders);
            int      i;

            LocalSolver[] solvs;
            int           s;

            // We first perform only the addition of orders to an empty schedule
            // This way we end up with filled in schedule that,
            //  depending on the LocalSolver used, can be quite optimised already
            #region AddOperation
            stati[taskID] = SolverStatus.Doing_Add;
            // Initialize some LocalSolvers
            solvs = new LocalSolver[]
            {
                new RandomHillClimbLocalSolver(start),
                new SaLocalSolver(start, 0.6, 0.99999)
            };
            foreach (LocalSolver ls in solvs)
            {
                ls.Init();
            }
            s = 0;  // Used to choose which LocalSolver is used to get the next state

            bool       stopAdd = false;
            i = 0; int noChangeAdd = 0; // Iteration counters
            while (!stopAdd)
            {
                LocalSolver solver = solvs[s];
                double[]    probs  = new double[] { 7 / 8.0, 1 / 8.0, 0, 0 };
                if (solver.GetNext(probs, OperationCount)) //Add, Delete, Transfer, Swap
                {
                    // The LocalSolver accepted a new state
                    noChangeAdd = 0;
                    // Check if next state is better than current best:
                    if (solver.schedule.Score < best.Score)
                    {
                        best = solver.schedule.ToResult();
                    }
                }
                else
                {
                    noChangeAdd++;
                }

                if (i % OptimizeInterval == 0)
                {
                    for (int opt = 0; opt < OptimizeIterations; opt++)
                    {
                        solver.schedule.OptimizeAllDays();
                    }
                }
                if (i % UpdateIterationStatusInverval == 0)
                {
                    iterationCounters[taskID] = i;
                }
                if (i % SwitchSearchAlgorithmInterval_AddPhase == 0)
                {
                    s = 1 - s;                                                  // Used to switch LocalSolver
                }
                stopAdd =
                    noChangeAdd == MaxNoChange_AddPhase ||
                    ++i == MaxIterations_AddPhase ||
                    UserInterrupt;
            }
            #endregion

            // Once we have a filled in schedule it makes more sense to perform the other operators
            // We generate opCount neighbors using the Add, Delete, Transfer (first delete than add) and Swap
            // Since opCount does not have to be equal to 4 (we have four operators) we use a probability distribution.
            // For each neighbor then with the given chance one of the operators in picked and used to generate a neigbor
            // Once again there is also the possibility to choose the LocalSolver
            //  that picks the next state from the neighbors
            #region AllOperations
            stati[taskID] = SolverStatus.Doing_All;
            // Initialize some LocalSolvers:
            solvs = new LocalSolver[]
            {
                new RandomHillClimbLocalSolver(start),
                new SaLocalSolver(start, 1, 0.99999)
            };
            foreach (LocalSolver ls in solvs)
            {
                ls.Init();
            }
            s = 1;

            bool       stop = false;
            i = 0; int noChange = 0; // Iteration counters
            while (!stop)
            {
                LocalSolver solv = solvs[s];
                // Try-out probability distributions, goal -> make them dynamic and dependent on iteration count
                //double[] probs = new double[] { 1, 0, 0, 0 }; // Add only
                //double[] probs = new double[] { 0, 0, 0, 1 }; // Swap only
                //double[] probs = new double[] { 2 / 12.0, 5 / 12.0, 5 / 12.0, 0 / 12.0 };
                double[] probs = new double[] { 1 / 12.0, 1 / 12.0, 5 / 12.0, 5 / 12.0 };
                if (solv.GetNext(probs, OperationCount)) //Add, Delete, Transfer, Swap
                {
                    // Solver accepted new state
                    noChange = 0;
                    // Check if next state is better than current best:
                    if (solv.schedule.Score < best.Score)
                    {
                        best = solv.schedule.ToResult();
                    }
                }
                else
                {
                    noChange++;
                }
                if (i % OptimizeInterval == 0)
                {
                    for (int opt = 0; opt < OptimizeInterval; opt++)
                    {
                        solv.schedule.OptimizeAllDays();
                    }
                }
                if (i % UpdateIterationStatusInverval == 0)
                {
                    iterationCounters[taskID] = i;
                }
                //if (i % SwitchSearchAlgorithmInterval_AllPhase == 0) s = 1 - s; // Used to switch LocalSolver
                stop = noChange == MaxNoChange_AllPhase ||
                       ++i == MaxIterations_AllPhase ||
                       UserInterrupt;
            }
            #endregion

            // Solver done, update status accordingly:
            stati[taskID] = SolverStatus.Done;
        }