private void ClearScheduler(SchedulerModel scheduler) { //scheduler.ProcessName = null; scheduler.Scheduler = null; scheduler.Process = null; scheduler.Jobs = null; }
public IActionResult Index(Guid id, PersonType shedulertype, string specialties) { var scheduler = new SchedulerModel(); scheduler.DoctorPatient = new DoctorPatientModel(); scheduler.DateStart = DateTime.Now.AddHours(1); scheduler.DateEnd = DateTime.Now.AddHours(2); if (shedulertype == PersonType.Doctor) { scheduler.DoctorPatient.DoctorId = id; scheduler.Specialties = specialties.Split(",").ToList(); scheduler.DoctorPatient.PatientId = Guid.Parse(HttpContext.GetIdentifier()); scheduler.Type = SchedulerType.Scheduler; } else { scheduler.DoctorPatient.PatientId = id; scheduler.DoctorPatient.DoctorId = Guid.Parse(HttpContext.GetIdentifier()); scheduler.Type = SchedulerType.Solicitation; scheduler.Specialties = specialties.Split(",").ToList(); } return(View(scheduler)); }
public void StartScheduler(string rootPath, int schId) { lock (objLock) { SchedulerModel scheduler = schedulers.FirstOrDefault(t => t.SchedulerId == schId); if (scheduler != null) { Process[] ps = Process.GetProcessesByName(scheduler.ProcessName); if (ps != null && ps.Length > 0) { throw new Exception("已经存在进程" + scheduler.ProcessName); } Process process = new Process(); ProcessStartInfo info = new ProcessStartInfo() { FileName = Path.Combine(rootPath, scheduler.Directory, scheduler.FileName), WindowStyle = ProcessWindowStyle.Normal, CreateNoWindow = false }; process.StartInfo = info; process.Start(); BindScheduler(scheduler, process); scheduler.Status = SchedulerStatus.Running; } } }
private bool CheckSchedulerExists(SchedulerModel scheduler) { NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.proxy"] = "true"; properties["quartz.scheduler.proxy.address"] = string.Format("tcp://localhost:{0}/QuartzScheduler", scheduler.Port); ISchedulerFactory factory = new StdSchedulerFactory(properties); try { if (SchedulerRepository.Instance.Lookup(scheduler.SchedulerName) == null) { scheduler.Scheduler = factory.GetScheduler(); } else { scheduler.Scheduler = factory.GetScheduler(scheduler.SchedulerName); } if (scheduler.Scheduler.IsShutdown == true) { return(false); } return(true); } catch (RemotingException ex) { return(false); } catch (Exception ex) { return(false); } }
/// <summary> /// Init window /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void InitWindow(object sender, DirectEventArgs e) { // init id var param = e.ExtraParams["Id"]; // parse id if (int.TryParse(param, out var id)) { // init window props if (id > 0) { // edit wdSetting.Title = @"Cập nhật thông tin chấm công"; wdSetting.Icon = Icon.Pencil; } // init id hdfId.Text = id.ToString(); // init model var model = new SchedulerModel(null); // check id if (id > 0) { var result = SchedulerController.GetById(id); if (result != null) { model = result; } } // set scheduler prop txtName.Text = model.Name; txtDescription.Text = model.Description; txtIntervalTime.Text = model.IntervalTime.ToString(); txtExpiredAfter.Text = model.ExpiredAfter.ToString(); txtArguments.Text = model.Arguments; chkEnable.Checked = model.Enabled; if (model.NextRunTime != null) { txtNextRuntime.Text = model.NextRunTime.Value.ToString("yyyy/MM/dd HH:mm"); } if (model.Id > 0) { // repeat type hdfSchedulerRepeatType.Text = ((int)model.RepeatType).ToString(); cbxSchedulerRepeatType.Text = model.RepeatTypeName; // scope hdfSchedulerScope.Text = ((int)model.Scope).ToString(); cbxSchedulerScope.Text = model.ScopeName; // status hdfSchedulerStatus.Text = ((int)model.Status).ToString(); cbxSchedulerStatus.Text = model.StatusName; } // show window wdSetting.Show(); } }
private TimeSpanFrequency ApplyTimeRange(SchedulerModel model) { return(model.IsSingleLanch == false ? TimeSpanFrequency.StartOnce(model.cTimeConst.TimeOfDay) : new TimeSpanFrequency(model.SingleLanchPeriod, (RhythmByTime) Enum.Parse(typeof(RhythmByTime), model.OccursEvery.ToString()), model.StartingAt.TimeOfDay, model.EndingAt.TimeOfDay)); }
public void KillProcess(int schId) { SchedulerModel scheduler = schedulers.FirstOrDefault(t => t.SchedulerId == schId); Process[] ps = Process.GetProcessesByName(scheduler.ProcessName); foreach (var p in ps) { p.Kill(); } }
public JsonResult Refresh(SchedulerModel model) { try { return(Json(new Sheduling().DescriptionFor(ApplySheduling(model)), JsonRequestBehavior.AllowGet)); } catch (Exception) { return(Json(string.Empty, JsonRequestBehavior.AllowGet)); } }
public TotalWorkTimeCostFunction(SchedulerModel model, WorkEligibilityChecker workEligibilityChecker, CompositeStateCalculator stateCalculator) { _underMinWorkTimeCost = DefaultCost * 0.5; _model = model ?? throw new ArgumentNullException(nameof(model)); _workEligibilityChecker = workEligibilityChecker ?? throw new ArgumentNullException(nameof(workEligibilityChecker)); _stateCalculator = stateCalculator ?? throw new ArgumentNullException(nameof(stateCalculator)); _longestShift = _model.Demands.Values .SelectMany(dArr => dArr) .Select(d => d.Shift) .OrderByDescending(s => s.Duration) .First(); }
public IHttpActionResult ScheduleCall([FromBody] SchedulerModel schedulerModel) { //var registry = new Registry(); //registry.Schedule<SampleJob>().ToRunNow(); //JobManager.Initialize(registry); JobManager.Initialize(new ScheduledJobRegistry(schedulerModel.Appointment)); //JobManager.AddJob(() => File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", "Test"), (s) => s.ToRunEvery(5).Seconds()); //JobManager.AddJob(() => Write(), s => s.ToRunEvery(2).Seconds()); JobManager.StopAndBlock(); return(Json(new { success = true, message = "Phone call incoming!" })); }
public WorkEligibilityChecker(SchedulerModel model) { _model = model ?? throw new ArgumentNullException(nameof(model)); _workEligibilityCheckers = new Func <Person, int, bool>[] { Unavailable, AlreadyHasAssignmentOnDay, WouldWorkLessThanMinConsecutiveDays, WouldWorkMoreThanMaxConsecutiveDays, WouldRestLessThanMinConsecutiveDayOff, WouldWorkMoreThanMaxWeekends }; }
public async Task <Tuple <ModelStateDictionary, Guid> > CreateAsync(SchedulerModel model) { ModelStateDictionary keyValuePairs = new ModelStateDictionary(); // todo validar se não é o 2 agendamento no mesmo horario var scheduler = mapper.Map <Scheduler>(model); var doctorPatient = await doctorPatientRepository.AddAsync(scheduler.DoctorPatient); scheduler.MeetAddressLink = "https://meet.google.com/wrc-ztqa-vji"; scheduler.DoctorPatientId = doctorPatient.Id; await schedulerrepository.AddAsync(scheduler); //todo pegar do google calendar return(new Tuple <ModelStateDictionary, Guid>(keyValuePairs, scheduler.Id)); }
public void ShutDownScheduler(int schId) { lock (objLock) { SchedulerModel scheduler = schedulers.FirstOrDefault(t => t.SchedulerId == schId); if (scheduler != null && scheduler.Scheduler != null && scheduler.Scheduler.IsShutdown == false) { scheduler.Scheduler.Shutdown(true); scheduler.Scheduler = null; scheduler.Jobs = null; scheduler.Process = null; scheduler.Status = SchedulerStatus.Stop; } } }
private void LoadEntity(SchedulerModel model) { const string def = @"<font color=""red"">{0}</font>"; //if (!IsFirstLoad) return; //_shaper = ParamId == 0 ? new PricelistShaper() : NSession.Get<PricelistShaper>(ParamId); //RatePlansSession = new HashSet<int>(_shaper..RatePlans.Select(x => x.ID)); model.CreatedOn = model.Id == 0 ? string.Format(def, "сегодня") : _shaper.CreatedOn.ToString(); //GetLabel("today") model.LastRun = model.Id == 0 ? string.Format(def, "никогда") : _shaper.LastRun.ToString(); //GetLabel("Never") model.NextRun = model.Id == 0 ? string.Format(def, "неизвестно") : _shaper.NextRun.ToString(); //GetLabel("Unknown") model.Duration = model.Id == 0 ? string.Format(def, "неизвестно") : _shaper.Duration.ToString(); //GetLabel("Unknown") model.Iteration = _shaper.Iteration.ToString(); //LoadSheduling(_shaper.Frequency); // model.Description = new Sheduling().DescriptionFor(_shaper.Frequency);// _sheduling.DescriptionFor(); }
/// <summary> /// Insert or Update scheduler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void InsertOrUpdate(object sender, DirectEventArgs e) { // init model var model = new SchedulerModel(null); // check id if (!string.IsNullOrEmpty(hdfId.Text) && Convert.ToInt32(hdfId.Text) > 0) { var result = SchedulerController.GetById(Convert.ToInt32(hdfId.Text)); if (result != null) { model = result; } } // set new props for model model.Name = txtName.Text; model.Description = txtDescription.Text; model.Arguments = txtArguments.Text; model.IntervalTime = !string.IsNullOrEmpty(txtIntervalTime.Text) ? Convert.ToInt32(txtIntervalTime.Text) : 0; model.ExpiredAfter = !string.IsNullOrEmpty(txtExpiredAfter.Text) ? Convert.ToInt32(txtExpiredAfter.Text) : 0; model.Enabled = chkEnable.Checked; model.SchedulerTypeId = Convert.ToInt32(hdfSchedulerType.Text); model.RepeatType = (SchedulerRepeatType)Enum.Parse(typeof(SchedulerRepeatType), hdfSchedulerRepeatType.Text); model.Scope = (SchedulerScope)Enum.Parse(typeof(SchedulerScope), hdfSchedulerScope.Text); model.Status = (SchedulerStatus)Enum.Parse(typeof(SchedulerStatus), hdfSchedulerStatus.Text); model.NextRunTime = DateTime.TryParseExact(txtNextRuntime.Text, "yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out var nextRunTime) ? nextRunTime : DateTime.Now; // check model id if (model.Id > 0) { // update SchedulerController.Update(model); } else { // insert SchedulerController.Create(model); } // hide window wdSetting.Hide(); // reload data gpScheduler.Reload(); }
public SchedulerAlgorithm(SchedulerModel model) { _model = model; _stateCalculator = new CompositeStateCalculator(_model.SchedulePeriod, _model.Calendar); _workEligibilityChecker = new WorkEligibilityChecker(_model); _costFunction = CreateCompositeCostFunction(_model); _schedulers = new SchedulerBase[] { //new MinDemandsScheduler(_model, _costFunction, _workEligibilityChecker, _stateCalculator), //new WeekendScheduler(_model, _costFunction, _workEligibilityChecker, _stateCalculator), new AllDemandsScheduler(_model, _costFunction, _stateCalculator, _workEligibilityChecker), new UntilMinTotalWorkTimeScheduler(_model, _stateCalculator, _workEligibilityChecker, _costFunction), new ReplaceSingleWeekendsWithDoubleWeekendsScheduler(_model, _stateCalculator, _workEligibilityChecker, _costFunction), new RemoveUnderMinConsecutiveShiftsScheduler(_model, _costFunction, _workEligibilityChecker), }; }
public async Task RefreshStopsAsync(eDirection direction = eDirection.None) { try { if (string.IsNullOrEmpty(DayOfWeek)) { return; } var schs = await new SchedulerController().ListWithChildrenAsync(); var sch = schs.Where(x => x.LongName == DayOfWeek); if (sch != null && sch.Any()) { _sch = sch.FirstOrDefault(); Stops = sch.FirstOrDefault() .Customers .OrderBy(x => x.Index) .ToList(); } else if (_sch != null) { int goTo = direction == eDirection.Next? 1: direction == eDirection.Previus? -1: 0; var ind = schs.IndexOf(_sch) + goTo; if (ind > 0) { _sch = schs[schs.IndexOf(_sch) + goTo]; Stops = _sch .Customers .OrderBy(x => x.Index) .ToList(); } else { Stops = new List <CustomerModel>(); } } } catch (Exception e) { Debug.WriteLine(e); await Message.DisplayAlertAsync(e.Message, Title, "Ok"); } }
private CompositeCostFunction CreateCompositeCostFunction(SchedulerModel model) { var(maxShiftOffRequestWeight, maxShiftOnRequestWeight) = ShiftRequestCostFunction.GetMaxWeights(model); var costFunctions = new CostFunctionBase[] { new WeekendWorkCostFunction(_model.Calendar), new TotalWorkTimeCostFunction(_model, _workEligibilityChecker, _stateCalculator), new ShiftRequestCostFunction(maxShiftOffRequestWeight, maxShiftOnRequestWeight), new ConsecutiveShiftCostFunction(_model.Calendar), new DayOffCostFunction(), new ValidShiftCostFunction(), new MaxShiftCostFunction(), new MinRestTimeCostFunction() }; return(new CompositeCostFunction(costFunctions)); }
private void BindScheduler(SchedulerModel scheduler, Process process) { scheduler.Process = process; NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.proxy"] = "true"; properties["quartz.scheduler.proxy.address"] = string.Format("tcp://localhost:{0}/QuartzScheduler", scheduler.Port); ISchedulerFactory factory = new StdSchedulerFactory(properties); try { if (SchedulerRepository.Instance.Lookup(scheduler.SchedulerName) == null) { scheduler.Scheduler = factory.GetScheduler(); } else { scheduler.Scheduler = factory.GetScheduler(scheduler.SchedulerName); } } catch (Exception ex) { string s = ex.Message; } scheduler.Jobs = new List <JobModel>(); var groups = scheduler.Scheduler.GetJobGroupNames(); foreach (var group in groups) { var jobkeys = scheduler.Scheduler.GetJobKeys(Quartz.Impl.Matchers.GroupMatcher <JobKey> .GroupContains(group)); foreach (var key in jobkeys) { var job = new JobModel() { GroupName = key.Group, JobName = key.Name }; scheduler.Jobs.Add(job); BindJobStatus(scheduler.Scheduler, job); } } }
public CallbackModel UploadScheduler() { try { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var part = new MultipartFormDataConverter(Request.Content); int schId = int.Parse(part.FormData["SChId"]); SchedulerModel scheduler = SchedulerManager.Instance.Schedulers.FirstOrDefault(t => t.SchedulerId == schId); if (scheduler != null) { string dir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath + scheduler.Directory); string fileName = string.Format("{0}-{1:yyyyMMddHHmmss}.zip", scheduler.SchedulerName, DateTime.Now); string fileFullName = Path.Combine(dir, fileName); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } var file = part.FileContents["fileUpload"]; file.Save(fileFullName); using (ZipFile zip1 = ZipFile.Read(fileFullName, new ReadOptions() { Encoding = Encoding.Default })) { foreach (ZipEntry e in zip1) { e.Extract(dir, ExtractExistingFileAction.OverwriteSilently); } } } return(new CallbackModel(true)); } catch (Exception ex) { return(new CallbackModel(false, ex.Message)); } }
protected void ScheduleJobWithDefaultTrigger <T>(string jobGroupName, string jobName) where T : IJob { JobBuilder builder = JobBuilder.Create <T>() .WithIdentity(jobName, jobGroupName) .WithDescription(jobGroupName + "." + jobName); IJobDetail job = builder.Build(); DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow); ITrigger trigger = TriggerBuilder.Create() .WithIdentity(TriggerName, jobGroupName) .StartAt(runTime) .WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1)) .Build(); _sched.ScheduleJob(job, trigger); Context = new SchedulerModel(_sched); }
public async Task <IActionResult> Index(SchedulerModel scheduler) { if (ModelState.IsValid) { var schedulervalidator = await schedulerService.CreateAsync(scheduler); if (!schedulervalidator.Item1.Any()) { if (scheduler.Type == SchedulerType.Scheduler) { return(RedirectToAction(nameof(DetailScheduler), new { schedulerId = schedulervalidator.Item2 })); } else { return(RedirectToAction(nameof(DetailSolicitation), new { schedulerId = schedulervalidator.Item2 })); } } } return(View(scheduler)); }
private List <SchedulerModel> GetSchedulersFromDB() { List <SchedulerModel> result = new List <SchedulerModel>(); SchedulerDAL dal = new SchedulerDAL(); var schs = dal.GetAllScheduler(); foreach (var sch in schs) { SchedulerModel item = new SchedulerModel() { SchedulerId = sch.SchedulerId, SchedulerName = sch.SchedulerName, Directory = sch.Directory, FileName = sch.FileName, Port = sch.Port, IsEnable = sch.IsEnable }; result.Add(item); } return(result); }
/// <summary> /// Creates this instance. /// </summary> private void Create(object exeName) { var schedulerData = new SchedulerModel { Author = "i95Dev", Id = SchedulerName, Description = Description, TaskFolder = SchedulerGroupName, Arguments = schedulerId.ToString(CultureInfo.CurrentCulture), Path = Constants.BaseDirectory + (string.IsNullOrEmpty(DialogLocator.MainAssemblyPath) & exeName != null ? Convert.ToString(exeName, Constants.DefaultCulture) : DialogLocator.MainAssemblyPath) + @".exe", WorkingDirectory = Constants.BaseDirectory, DaysInterval = 1, RepetitionInterval = IntervalTime }; bool result = CreateScheduler(schedulerData, true); if (result) { LoadSchedulerStatus(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(route => { route.MapRoute( name: "defaultApi", template: "api/{controller}/{action}/{id?}"); }); //hangfire dashboard JobStorage.Current = new Hangfire.SqlServer.SqlServerStorage(Configuration.GetConnectionString("HangFireDBConnectionString")); var schedulerModel = new SchedulerModel(); schedulerModel.AddSchedulerJob(); app.UseHangfireDashboard("/jobs", new DashboardOptions { AppPath = "" }); app.UseHangfireServer(); }
private SchedulerModel ReviseScheduler(SchedulerModel scheduler) { if (string.IsNullOrEmpty(scheduler.ProcessName)) { ClearScheduler(scheduler); } else { Process[] ps = Process.GetProcessesByName(scheduler.ProcessName); if (ps != null && ps.Length > 0) { try { if (CheckSchedulerExists(scheduler) == false) { ClearScheduler(scheduler); scheduler.Status = SchedulerStatus.ProcessRunning; } else { BindScheduler(scheduler, ps[0]); scheduler.Status = SchedulerStatus.Running; } } catch (RemotingException ex) { throw ex;///TODO????? } } else { ClearScheduler(scheduler); scheduler.Status = SchedulerStatus.Stop; } } return(scheduler); }
public RemoveUnderMinConsecutiveShiftsScheduler(SchedulerModel model, CostFunctionBase costFunction, WorkEligibilityChecker workEligibilityChecker) : base(model, costFunction, workEligibilityChecker) { }
// summary: // initialize uc models public void Init(BusinessObjectServiceClient boServiceClient) { var instanceContext = new InstanceContext(this); _model = new SchedulerModel(boServiceClient, instanceContext); }
public ActionResult Index(int?id, string type) { SchedulerModel model; try { if (id.HasValue) { _shaper = Db <WebEnvironmentFiact> .NSession.Get <Sheduler>(id); } else { switch (type) { case "import": _shaper = new ImportSheduling(); break; case "export": _shaper = new ExportSheduling(); break; case "eitp_hour": _shaper = new EitpHourScheduling(); break; case "eitp_daily": _shaper = new EitpDailyScheduling(); break; default: _shaper = new MoreSheduling(); break; } } model = LoadSheduling(_shaper.Frequency); model.Type = _shaper.Type; model.IsEnabled = _shaper.IsEnabled; model.Name = _shaper.Name; model.IsKill = _shaper.IsKill; model.Runtime = _shaper.Runtime; model.Param = _shaper.Param; model.TimeGetData = _shaper.TimeGetData; if (_shaper.Frequency is SingleLanchFrequency) { model.FrequencyType = 0; } else { model.FrequencyType = 1; } model.Id = _shaper.Id; LoadEntity(model); } catch (Exception e) { model = new SchedulerModel(); } return(View(model)); }
private SchedulerModel LoadSheduling(SheduleFrequencyProperty sheduler) { SchedulerModel model = new SchedulerModel(); switch (sheduler.Occurs) { case RhythmByDate.OneTime: model.cDate = _shaper.Frequency.DurationFrom.Add(sheduler.DailyFrequency.StartingAt); break; case RhythmByDate.Daily: model.DailyPeriod = sheduler.Period; break; case RhythmByDate.Weekly: model.WeeklyPeriod = sheduler.Period; List <DayOfWeek> recuring = ((WeeklyFrequency)sheduler).RecuringDays; model.Monday = recuring.Contains(DayOfWeek.Monday); model.Tuesday = recuring.Contains(DayOfWeek.Tuesday); model.Wednesday = recuring.Contains(DayOfWeek.Wednesday); model.Thursday = recuring.Contains(DayOfWeek.Thursday); model.Friday = recuring.Contains(DayOfWeek.Friday); model.Saturday = recuring.Contains(DayOfWeek.Saturday); model.Sunday = recuring.Contains(DayOfWeek.Sunday); break; case RhythmByDate.Monthly: model.MonthlyPeriod = model.tbxMonthNumFor = sheduler.Period; if (((MonthlyFrequency)sheduler).IsDefinedByDay) { model.RblMonthDetail = false; model.DayOffset = ((MonthlyFrequency)sheduler).DayOffset; } else { model.RblMonthDetail = true; KeyValuePair <RhythmByWeek, DayOfWeek>?datePart = ((MonthlyFrequency)sheduler).DayOfWeek; if (!datePart.HasValue) { return(model); } foreach (var item in model.WeekPartList) { item.Selected = item.Value == ((int)datePart.Value.Key).ToString(); if (item.Selected) { model.ddlWeekPart = ((int)datePart.Value.Key); } } foreach (var item in model.DayOfWeekList) { item.Selected = item.Value == ((int)datePart.Value.Value).ToString(); if (item.Selected) { model.ddlWeeks = (int)datePart.Value.Value; } } } break; } foreach (var item in model.DateRhythmList) { item.Selected = item.Value == ((int)sheduler.Occurs).ToString(); if (item.Selected) { model.ddlDateRhythm = (int)sheduler.Occurs; } } TimeSpanFrequency daily = sheduler.DailyFrequency; if (daily.IsSingleLanch) { model.cTimeConst = DateTime.Now.Date.Add(daily.StartingAt); } else { model.IsSingleLanch = true; //foreach (ListItem item in IsSingleLanch.Items) //{ // item.Selected = item.Value == @"1"; //} foreach (var item in model.RhythmByTimeList) { item.Selected = item.Value == ((int)daily.OccursEvery).ToString(); if (item.Selected) { model.OccursEvery = (int)daily.OccursEvery; } } model.StartingAt = new DateTime().Add(daily.StartingAt); model.EndingAt = new DateTime().Add(daily.EndingAt); model.SingleLanchPeriod = daily.Period; } model.DurationFrom = sheduler.DurationFrom; if (!sheduler.IsInfinite) { //foreach (ListItem item in rblStopDetail.Items) // item.Selected = item.Value == @"1"; model.IsInfinite = false; model.DurationTo = sheduler.DurationTo; } else { model.IsInfinite = true; } return(model); }