基于队列等待时长变更AnyLogic中Agent颜色的实现方案
Great question—this is a super common scenario in AnyLogic DES models, and I totally get why the basic timeout approach feels risky (it can mess up queue order if you’re not careful). Let’s walk through two solid solutions that’ll let you color-code agents waiting too long without disrupting their position in line:
Method 1: Track Wait Time with a Periodic Check
This approach directly monitors each agent’s time in the queue and updates colors in-place, so your queue order stays intact.
- Add a tracking parameter to your Agent: Create a
doubleparameter (e.g.,timeEnteredQueue) in your agent type to store when they joined the queue. - Set the entry time: In your queue’s
onEnteraction, add:agent.timeEnteredQueue = time(); - Create a periodic check event: Add an
Eventto your main model with a short repeat interval (like 0.1 seconds for responsiveness). In its action, loop through all agents in the queue:for (int i = 0; i < myQueue.size(); i++) { MyAgent currentAgent = myQueue.get(i); double timeWaited = time() - currentAgent.timeEnteredQueue; if (timeWaited > WAIT_THRESHOLD) { currentAgent.setColor(Color.RED); // Your desired timeout color } else { currentAgent.setColor(Color.GREEN); // Reset to default if needed } } - Clean up on exit: In the queue’s
onExitaction, reset the agent’s color to its default to avoid carryover to other parts of the model.
Since we’re just iterating through the queue’s existing list and updating colors in-place, the agent order never changes.
Method 2: Agent-Specific Timeout (No Global Event)
If you prefer a more object-oriented approach, attach a timeout to each agent that only updates their color—never removes them from the queue.
- Add a timeout event to your Agent: Create an
Event(e.g.,triggerWaitColorChange) in your agent type. Set its delay to your wait threshold, and in its action:// Only change color if the agent is still in the queue if (this.getContainer() instanceof Queue && ((Queue)this.getContainer()).contains(this)) { setColor(Color.RED); } - Start the timeout on queue entry: In the queue’s
onEnteraction, restart the agent’s timeout:agent.triggerWaitColorChange.restart(WAIT_THRESHOLD); - Cancel on exit: In the queue’s
onExitaction, cancel the timeout and reset the agent’s color:agent.triggerWaitColorChange.cancel(); agent.setColor(Color.GREEN);
This method is efficient because the timeout only triggers when an agent has waited long enough, and the check ensures we don’t modify colors for agents that already left the queue.
Quick Tips
- Queue Visualization: Make sure your queue’s shape is set to display agent colors—most default queue visuals inherit the agent’s color automatically.
- Performance: For very large queues, the agent-specific timeout method is more lightweight than a global periodic check, but both work reliably for most model sizes.
内容的提问来源于stack exchange,提问作者Emile Zankoul




