public Future <T> Start <T> (ISchedulable <T> task, TaskExecutionPolicy executionPolicy = TaskExecutionPolicy.Default) { var future = new Future <T>(); Start(future, task, executionPolicy); return(future); }
public IFuture Start(ISchedulable schedulable) { var f = Scheduler.Start(schedulable, TaskExecutionPolicy.RunAsBackgroundTask); OwnedFutures.Add(f); return(f); }
public void DisableJobsOfDevice(ISchedulable device) { if (device.JobsCreated) { DeleteAllJobsOfDevice(device); } }
public void EnableJobsOfDevice(ISchedulable device) { if (!device.JobsCreated) { CreateAllJobsForDevice(device); } }
/// <summary> /// Returns the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public override bool GetNext(out ISchedulable next, List <ISchedulable> choices, ISchedulable current) { var enabledChoices = choices.Where(choice => choice.IsEnabled).ToList(); if (enabledChoices.Count == 0) { next = null; return(false); } ScheduledSteps++; if (enabledChoices.Count > 1) { if (!ShouldCurrentMachineChange() && current.IsEnabled) { next = current; return(true); } } int idx = RandomNumberGenerator.Next(enabledChoices.Count); next = enabledChoices[idx]; return(true); }
/// <summary> /// Returns the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public virtual bool GetNext(out ISchedulable next, List <ISchedulable> choices, ISchedulable current) { var currentMachineIdx = choices.IndexOf(current); var orderedMachines = choices.GetRange(currentMachineIdx, choices.Count - currentMachineIdx); if (currentMachineIdx != 0) { orderedMachines.AddRange(choices.GetRange(0, currentMachineIdx)); } var enabledChoices = orderedMachines.Where(choice => choice.IsEnabled).ToList(); if (enabledChoices.Count == 0) { next = null; return(false); } int idx = 0; while (RemainingDelays.Count > 0 && ScheduledSteps == RemainingDelays[0]) { idx = (idx + 1) % enabledChoices.Count; RemainingDelays.RemoveAt(0); Logger.WriteLine("<DelayLog> Inserted delay, '{0}' remaining.", RemainingDelays.Count); } next = enabledChoices[idx]; ScheduledSteps++; return(true); }
public void Activate(ISchedulable source, Loc target) { if (!(source is Actor sourceActor)) { return; } // Relies on GetTilesInRange being called in the targetting phase. // Also requires the hook to be considered a projectile so that the trail is saved. IEnumerable <Loc> path = Area.Trail; List <Loc> collisionPath = new List <Loc>(); // Walk along the path, stopping when something is hit and save the collision tile. Option <Loc> collision = Option.None <Loc>(); foreach (Loc point in path) { if (!Game.Map.Field[point].IsWalkable) { collision = Option.Some(point); break; } collisionPath.Add(point); } // Don't do anything if we target a blocked square next to us. if (collisionPath.Count == 0) { return; } LayerInfo currentLayer = Game.StateHandler.CurrentLayer; collision.Match( some: pos => { Game.Map.GetActor(pos).Match( some: actor => { // If an Actor is hit, pull the target in. Loc deposit = collisionPath[0]; Game.Map.SetActorPosition(actor, deposit); Animation = Option.Some <IAnimation>(new HookAnimation(currentLayer, sourceActor, collisionPath, true, actor)); }, none: () => { // If something else got hit, it must be a wall or door. In either case, pull // the source towards the target. Loc deposit = collisionPath.Last(); Game.Map.SetActorPosition(sourceActor, deposit); Animation = Option.Some <IAnimation>(new HookAnimation(currentLayer, sourceActor, collisionPath, false)); }); }, none: () => { // Otherwise don't do anything. Animation = Option.Some <IAnimation>(new HookAnimation(currentLayer, sourceActor, collisionPath, true)); }); }
/// <summary> /// Returns the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public bool TryGetNext(out ISchedulable next, List <ISchedulable> choices, ISchedulable current) { var enabledChoices = choices.Where(choice => choice.IsEnabled).ToList(); if (enabledChoices.Count == 0) { next = null; return(false); } this.ExploredSteps++; if (enabledChoices.Count > 1) { if (!this.ShouldCurrentMachineChange() && current.IsEnabled) { next = current; return(true); } } int idx = this.Random.Next(enabledChoices.Count); next = enabledChoices[idx]; return(true); }
private bool Update() { // Dequeue and execute the handler for each entities in the turn queue until empty. while (_eventSet.Count > 0) { if (_stopping) { _eventSet.Clear(); _stopping = false; return(false); } ISchedulable current = _eventSet.Peek(); ICommand action = current.Act(); if (Execute(current, action)) { _eventSet.PopMax(); if (current.Lifetime == 0) // -1 is used as nonexpiring { RemoveActor(current); } } else { return(false); } } return(true); }
public IWorkflowBuilder Attach(ISchedulable schedulable) { StageAction stageAction; if (schedulable is IActivity) { stageAction = StageAction.NewScheduleActivity((IActivity)schedulable); } else if (schedulable is IWorkflow) { stageAction = StageAction.NewStartChildWorkflow((IWorkflow)schedulable); } else { throw new NotSupportedException(string.Format( "Type [{0}] is not a supported schedulable action", schedulable.GetType())); } var stage = new Stage(stages.Count, stageAction); stages.Add(stage); return(this); }
// Heals the target by amount up to its maximum health. public void Activate(ISchedulable source, Loc target) => Game.Map.GetActor(target).MatchSome(targetUnit => { int healing = targetUnit.TakeHealing(_power); Game.MessageHandler.AddMessage( $"{source.Name} healed {targetUnit.Name} by {healing} damage"); });
public IFuture Start(ISchedulable task, TaskExecutionPolicy executionPolicy = TaskExecutionPolicy.Default) { var future = new Future <object>(); Start(future, task, executionPolicy); return(future); }
private void CreateAllJobsForDevice(ISchedulable device) { var validActions = ValidJobActionsForDevice(device); foreach (var action in validActions) { TimeSpan timeSpanUtc; if (TryGetTimeSpan(device, action, out timeSpanUtc)) { Type jobType; if (TryGetJobType(device, action, out jobType)) { var job = JobBuilder.Create(jobType) .WithIdentity($"{device.Description}/{action}", device.DeviceTypeName) .UsingJobData("groupName", device.DeviceTypeName) .Build(); job.JobDataMap.Put(device.DeviceTypeName, device); var trigger = TriggerBuilder.Create() .WithIdentity($"{device.Description}/{action}", device.DeviceTypeName) .StartNow() .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(timeSpanUtc.Hours, timeSpanUtc.Minutes) .InTimeZone(TimeZoneInfo.Utc)) .ForJob(job) .Build(); if (trigger != null) { _scheduler.ScheduleJob(job, trigger); device.JobsCreated = true; } } } } }
/// <summary> /// Forces the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public void ForceNext(ISchedulable next, List <ISchedulable> choices, ISchedulable current) { ISchedulable temp = next; bool res = GetNextHelper(ref temp, choices, current); Contract.Assert(res, "DPOR scheduler refused to schedule a forced choice."); Contract.Assert(temp == next, "DPOR scheduler changed forced next choice."); }
public ActionCommand(ISchedulable source, IAction action, IEnumerable <Loc> targets) { Source = source; EnergyCost = action.EnergyCost; _action = action; _targets = targets; }
public ISchedulableAwaiter(ISchedulable schedulable) { Registration = new CancellationScope.Registration(TaskScheduler.Current); Schedulable = schedulable; var ts = (TaskScheduler)Registration.Scheduler; Future = ts.Start(schedulable, TaskExecutionPolicy.RunWhileFutureLives); }
public DelayAttack(ISchedulable source, IAction action, IEnumerable <Loc> targets) { Energy = 0; ActivationEnergy = action.Speed; _source = source; _action = action; Targets = targets; }
/// <summary> /// Returns the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public bool GetNext(out ISchedulable next, List <ISchedulable> choices, ISchedulable current) { if (IsReplaying) { var enabledChoices = choices.Where(choice => choice.IsEnabled).ToList(); if (enabledChoices.Count == 0) { next = null; return(false); } try { if (ScheduledSteps >= ScheduleTrace.Count) { ErrorText = "Trace is not reproducible: execution is longer than trace."; throw new InvalidOperationException(ErrorText); } ScheduleStep nextStep = ScheduleTrace[ScheduledSteps]; if (nextStep.Type != ScheduleStepType.SchedulingChoice) { ErrorText = "Trace is not reproducible: next step is not a scheduling choice."; throw new InvalidOperationException(ErrorText); } next = enabledChoices.FirstOrDefault(choice => choice.Id == nextStep.ScheduledMachineId); if (next == null) { ErrorText = $"Trace is not reproducible: cannot detect id '{nextStep.ScheduledMachineId}'."; throw new InvalidOperationException(ErrorText); } } catch (InvalidOperationException ex) { if (SuffixStrategy == null) { if (!Configuration.DisableEnvironmentExit) { Error.ReportAndExit(ex.Message); } next = null; return(false); } else { IsReplaying = false; return(SuffixStrategy.GetNext(out next, choices, current)); } } ScheduledSteps++; return(true); } return(SuffixStrategy.GetNext(out next, choices, current)); }
public void Activate(ISchedulable source, Loc target) { if (source is Actor actor && Game.Map.Field[target].IsWalkable) { Loc prevLoc = actor.Loc; Game.Map.SetActorPosition(actor, target); Animation = Option.Some <IAnimation>(new MoveAnimation(Game.StateHandler.CurrentLayer, actor, prevLoc)); } }
public AttackCommand(ISchedulable source, int timeCost, double power, IEnumerable <Loc> targets, Option <IAnimation> animation, bool ignoreselfdamage = false) { Source = source; TimeCost = timeCost; Animation = animation; Targets = targets.ToList(); _power = power; _ignoreselfdamage = ignoreselfdamage; }
public void Activate(ISchedulable source, Loc target) => Game.Map.GetActor(target).MatchSome(targetUnit => { targetUnit.StatusHandler.AddStatus(Statuses.StatusType.Burning, 10); Game.MessageHandler.AddMessage(source is Fire ? $"{targetUnit.Name} caught on fire!" : $"{source.Name} set {targetUnit.Name} on fire!"); });
// Queues a task to the scheduler. internal void Enqueue(ISchedulable task) { if (!_tasks.Contains(task)) { lock (_tasks) { _tasks.Add(task); } } }
internal void Dequeue(ISchedulable task) { if (_tasks.Contains(task)) { lock (_tasks) { _tasks.Remove(task); } } }
public static void AddScheduler(ISchedulable s) { if (s is null || schedulers.Contains(s)) { return; } schedulers.Add(s); Log.Info("Added new scheduler: " + s.SchedulerName); }
/// <summary> /// Returns the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public bool TryGetNext(out ISchedulable next, List <ISchedulable> choices, ISchedulable current) { if (this.BoundedDFS.HasReachedMaxSchedulingSteps()) { return(this.Random.TryGetNext(out next, choices, current)); } { return(this.BoundedDFS.TryGetNext(out next, choices, current)); } }
/// <summary> /// Adds a new object to the Schedule and places it at the current time /// plus the object's Time property. /// </summary> /// <param name="schedulable">The schedulable object to add.</param> public void Add(ISchedulable schedulable) { int key = time + schedulable.Time; if (!schedulables.ContainsKey(key)) { schedulables.Add(key, new List <ISchedulable>()); } schedulables[key].Add(schedulable); }
public static ISchedulable GetRoot(this ISchedulable self) { var current = self; while (current.Parent != null) { current = current.Parent; } return(current); }
public void PostSchedule(ISchedulable s) { if (CurrentIsFirst) { secondQueue.Enqueue(s); } else { firstQueue.Enqueue(s); } }
/// <summary> /// Returns the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public bool GetNext(out ISchedulable next, List <ISchedulable> choices, ISchedulable current) { var enabledChoices = choices.Where(choice => choice.IsEnabled).ToList(); if (enabledChoices.Count == 0) { next = null; return(false); } SChoice nextChoice = null; List <SChoice> scs = null; if (SchIndex < ScheduleStack.Count) { scs = ScheduleStack[SchIndex]; } else { scs = new List <SChoice>(); foreach (var task in enabledChoices) { scs.Add(new SChoice(task.Id)); } ScheduleStack.Add(scs); } nextChoice = scs.FirstOrDefault(val => !val.IsDone); if (nextChoice == null) { next = null; return(false); } if (SchIndex > 0) { var previousChoice = ScheduleStack[SchIndex - 1].Last(val => val.IsDone); previousChoice.IsDone = false; } next = enabledChoices.Find(task => task.Id == nextChoice.Id); nextChoice.IsDone = true; SchIndex++; if (next == null) { return(false); } ScheduledSteps++; return(true); }
/// <summary> /// Forces the next choice to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public void ForceNext(ISchedulable next, List <ISchedulable> choices, ISchedulable current) { if (this.PrefixStrategy.HasReachedMaxSchedulingSteps()) { this.SuffixStrategy.ForceNext(next, choices, current); } else { this.PrefixStrategy.ForceNext(next, choices, current); } }
public void ScheduleDelayedEvent(ISchedulable subject, IValueStructure value, TimeSpan delay) { if(delay < TimeSpan.Zero) return; if(delay == TimeSpan.Zero) ScheduleDeltaEvent(subject, value); else { _schedule.ScheduleDelayedEvent(subject, value, delay); _timeline.InsertTime(delay); } }
public void ScheduleDelayedEvent(ISchedulable subject, IValueStructure value, TimeSpan delay) { LinkedList<SchedulerEventItem> timeline; if(!_delayedEvents.TryGetValue(subject.InstanceId, out timeline)) { timeline = new LinkedList<SchedulerEventItem>(); _delayedEvents.Add(subject.InstanceId, timeline); } if(timeline.Count == 0) { timeline.AddFirst(new SchedulerEventItem(subject, value, delay)); return; } TimeSpan d = TimeSpan.Zero; LinkedListNode<SchedulerEventItem> node = timeline.First; while(true) { if(d + node.Value.TimeSpan == delay) //already there... { TimeSpan relativeDelay = node.Value.TimeSpan; RemoveAllAfterIncluding(timeline, node); timeline.AddLast(new SchedulerEventItem(subject, value, relativeDelay)); return; } if(d + node.Value.TimeSpan > delay) //later events available { TimeSpan relativeDelay = delay - d; RemoveAllAfterIncluding(timeline, node); timeline.AddLast(new SchedulerEventItem(subject, value, relativeDelay)); return; } if(node.Next == null) //last { TimeSpan relativeDelay = delay - d - node.Value.TimeSpan; timeline.AddLast(new SchedulerEventItem(subject, value, relativeDelay)); return; } d += node.Value.TimeSpan; node = node.Next; } }
public IWorkflowBuilder Attach(ISchedulable schedulable) { StageAction stageAction; if (schedulable is IActivity) { stageAction = StageAction.NewScheduleActivity((IActivity)schedulable); } else if (schedulable is IWorkflow) { stageAction = StageAction.NewStartChildWorkflow((IWorkflow)schedulable); } else { throw new NotSupportedException(string.Format( "Type [{0}] is not a supported schedulable action", schedulable.GetType())); } var stage = new Stage(stages.Count, stageAction); stages.Add(stage); return this; }
public SchedulerEventItem(ISchedulable subject, IValueStructure value, TimeSpan timeSpan) { _subject = subject; _value = value; _timeSpan = timeSpan; }
public void ScheduleDelayedEvent(ISchedulable subject, IValueStructure value, TimeSpan delay) { GetCurrentScheduler().ScheduleDelayedEvent(subject, value, delay); }
string GetStatus(ISchedulable task) { if (task.IsWaiting) { return "Waiting"; } else if (task.IsRunning) { return "Running"; } else { return "Finished"; } }
void ScheduleNextStepForSchedulable(ISchedulable value) { if (value is WaitForNextStep) { _Scheduler.QueueWorkItemForNextStep(_QueueStep); } else if (value is Yield) { QueueStep(); } else { var temp = _Scheduler.Start(value, TaskExecutionPolicy.RunWhileFutureLives); SetWakeConditionAndSubscribe(temp, true); } }
public void ScheduleDeltaEvent(ISchedulable subject, IValueStructure value) { GetCurrentScheduler().ScheduleDeltaEvent(subject, value); }
void ScheduleNextStepForSchedulable (ISchedulable value) { if (value is WaitForNextStep) { _Scheduler.AddStepListener(_QueueStep); } else if (value is Yield) { QueueStep(); } else { var temp = _Scheduler.Start(value, TaskExecutionPolicy.RunWhileFutureLives); SetWakeCondition(temp, true); temp.RegisterOnComplete(_QueueStepOnComplete); } }
public IWorkflowBuilder Attach(ISchedulable[] schedulables, Func<Dictionary<int, string>, string> reducer) { var fsharpReducer = FuncConvert.ToFSharpFunc(new Converter<Dictionary<int, string>, string>(reducer)); var stageAction = StageAction.NewParallelActions(schedulables, fsharpReducer); var stage = new Stage(stages.Count, stageAction); stages.Add(stage); return this; }
public IFuture Start(ProcessInfo process, ISchedulable task) { OwnedFutureSet of = null; if (!_OwnedFutures.TryGetValue(process, out of)) { of = new OwnedFutureSet(); _OwnedFutures[process] = of; } var f = process.Start(task); of.Add(f); return f; }
public void ScheduleDeltaEvent(ISchedulable subject, IValueStructure value) { _deltaEvents.Push(new SchedulerEventItem(subject, value, TimeSpan.Zero)); }