Bird
Raised Fist0
ROSframework~15 mins

Preempting actions in ROS - Deep Dive

Choose your learning style10 modes available
Overview - Preempting actions
What is it?
Preempting actions in ROS means stopping or interrupting a running task before it finishes. It allows a robot or system to change its current behavior quickly when new commands or priorities come in. This is useful when the robot needs to respond to urgent changes or avoid conflicts. Preempting helps keep the system flexible and responsive.
Why it matters
Without preempting, a robot would have to finish its current task before starting a new one, which can cause delays or unsafe situations. For example, if a robot is moving to a location but suddenly needs to stop to avoid an obstacle, preempting lets it cancel the move immediately. This makes robots safer and more efficient in real-world environments where things change fast.
Where it fits
Before learning preempting actions, you should understand basic ROS concepts like nodes, topics, and the actionlib package for long-running tasks. After mastering preempting, you can explore advanced robot behavior design, multi-task coordination, and real-time control systems.
Mental Model
Core Idea
Preempting actions lets a robot stop or replace its current task instantly when a higher priority or new command arrives.
Think of it like...
It's like when you're cooking and suddenly the phone rings; you pause or stop cooking to answer the call because it's more urgent.
┌───────────────┐
│ Start Action  │
└──────┬────────┘
       │ Running
       ▼
┌───────────────┐
│ Preempt Signal│
└──────┬────────┘
       │ Interrupt
       ▼
┌───────────────┐
│ Stop Current  │
│   Action      │
└──────┬────────┘
       │ Start New
       ▼
┌───────────────┐
│ New Action    │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding ROS Actions Basics
🤔
Concept: Learn what ROS actions are and how they manage long tasks with feedback and results.
ROS actions let a robot perform tasks that take time, like moving or picking objects. They use an action server to run the task and an action client to send goals and get updates. Actions can provide feedback during execution and a final result when done.
Result
You can start and monitor tasks that take time in ROS, unlike simple commands that finish immediately.
Understanding actions is key because preempting only makes sense when tasks can run and be interrupted over time.
2
FoundationHow Action Clients and Servers Communicate
🤔
Concept: Learn the communication flow between action clients and servers in ROS.
The client sends a goal to the server. The server starts the task and sends feedback as it progresses. When done, the server sends a result. The client can also cancel or preempt the goal to stop the task early.
Result
You know how commands flow and how the client can influence the server's task.
Knowing this communication helps you see where preempting fits as a client request to stop or replace a task.
3
IntermediateWhat Preempting Means in ROS Actions
🤔Before reading on: do you think preempting cancels the task immediately or waits for the server to finish? Commit to your answer.
Concept: Preempting is a request from the client to the server to stop the current goal and optionally start a new one.
When a client sends a new goal while the server is busy, it can preempt the current goal. The server receives a preempt request and should stop the current task safely, then start the new goal. Preempting is cooperative: the server decides how to handle it.
Result
The robot can switch tasks quickly without waiting for the first task to finish naturally.
Understanding that preempting is a polite request, not a forced stop, helps avoid bugs where servers ignore or mishandle preempt requests.
4
IntermediateImplementing Preempt Callbacks in Servers
🤔Before reading on: do you think the server automatically stops on preempt or needs explicit code? Commit to your answer.
Concept: Servers must explicitly check for preempt requests and handle them in code to stop tasks properly.
In the server code, you add a preempt callback or check regularly if a preempt request arrived. When detected, the server stops the current operation, sets the goal state to preempted, and cleans up. This ensures the server responds correctly to client requests.
Result
Your server can stop tasks mid-way and switch to new goals safely.
Knowing that preempting requires explicit handling prevents servers from ignoring preempt requests and causing unresponsive behavior.
5
IntermediateClient-Side Preempting with New Goals
🤔
Concept: Clients can preempt by sending a new goal or canceling the current one.
To preempt, the client sends a new goal while the old one is active. This signals the server to stop the old task and start the new one. Alternatively, the client can cancel the current goal if no replacement is needed.
Result
Clients control the robot's tasks dynamically, adapting to new commands or priorities.
Understanding client control over preempting helps design responsive robot behaviors that can adapt on the fly.
6
AdvancedHandling Preempt Race Conditions and Safety
🤔Before reading on: do you think preempting can cause inconsistent robot states if not handled carefully? Commit to your answer.
Concept: Preempting can cause race conditions if the server changes state while stopping a task, so careful synchronization is needed.
When preempting, the server must ensure the robot is left in a safe state. For example, if moving, it should stop motors cleanly. Use locks or flags to avoid conflicts between task code and preempt handling. Test edge cases where preempt arrives during critical operations.
Result
Your robot behaves safely and predictably even when tasks are interrupted suddenly.
Knowing the risks of race conditions with preempting helps prevent crashes or unsafe robot behavior.
7
ExpertAdvanced Preempting: Nested and Stacked Goals
🤔Before reading on: can a server handle multiple preempt requests at once or nested preemptions? Commit to your answer.
Concept: Complex systems may receive multiple preempt requests quickly or have nested goals; managing these requires advanced state machines and queues.
In advanced setups, servers track goal states carefully, queue incoming goals, and handle multiple preemptions gracefully. This avoids losing commands or leaving tasks half-finished. Some systems implement priority queues or layered preempt logic to manage competing requests.
Result
Robots can handle complex, rapid command changes without errors or lost tasks.
Understanding nested preemptions and goal management is crucial for building robust, real-world robot controllers.
Under the Hood
ROS actions use a communication protocol over topics and services. When a client sends a new goal, the action server receives a preempt request message. The server's internal state machine transitions from ACTIVE to PREEMPTING, triggering callbacks or checks in the server code. The server then stops the current task, cleans resources, and starts the new goal. This cooperative mechanism relies on the server polling or callbacks to detect preempt requests and respond accordingly.
Why designed this way?
ROS actions were designed to handle long-running tasks asynchronously with feedback. Preempting was added to allow flexibility and responsiveness without forcing abrupt stops that could cause unsafe states. The cooperative design lets servers decide how to safely stop tasks, balancing responsiveness with stability. Alternatives like forced termination were rejected because they risked leaving hardware or software in inconsistent states.
Client sends new goal
      │
      ▼
┌───────────────┐
│ Action Server │
│  State:      │
│  ACTIVE      │
└──────┬────────┘
       │ Receives preempt request
       ▼
┌───────────────┐
│ State:       │
│ PREEMPTING   │
│ Calls preempt│
│ callback    │
└──────┬────────┘
       │ Stops current task
       ▼
┌───────────────┐
│ State:       │
│ READY for   │
│ new goal    │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does preempting force the server to stop immediately without any code changes? Commit yes or no.
Common Belief:Preempting automatically stops the server's task immediately without extra code.
Tap to reveal reality
Reality:The server must explicitly check for preempt requests and handle stopping; otherwise, it keeps running the current task.
Why it matters:Ignoring this leads to unresponsive servers that ignore preempt requests, causing delays and unsafe robot behavior.
Quick: Can a client preempt a goal by just sending a cancel request? Commit yes or no.
Common Belief:Canceling a goal is the same as preempting it with a new goal.
Tap to reveal reality
Reality:Canceling stops the current goal without replacement; preempting replaces the current goal with a new one.
Why it matters:Confusing these causes unexpected robot behavior, like stopping when a new task was intended.
Quick: Does preempting guarantee the robot stops instantly and safely? Commit yes or no.
Common Belief:Preempting guarantees immediate and safe stopping of the robot's current action.
Tap to reveal reality
Reality:Preempting requests a stop, but the server must implement safe stopping logic; otherwise, the robot may continue or stop unsafely.
Why it matters:Assuming automatic safety can cause hardware damage or accidents if the server lacks proper preempt handling.
Quick: Can multiple preempt requests be handled simultaneously without issues? Commit yes or no.
Common Belief:Servers can handle multiple preempt requests at once without special management.
Tap to reveal reality
Reality:Handling multiple preemptions requires careful state management; otherwise, commands can be lost or cause conflicts.
Why it matters:Ignoring this leads to unpredictable robot behavior in complex systems with rapid command changes.
Expert Zone
1
Preempting is cooperative, so servers can delay or reject preempt requests if stopping immediately is unsafe, requiring careful design.
2
Some action servers implement goal queues and priorities to manage preemptions, allowing more complex task scheduling.
3
Preempt callbacks must be thread-safe and non-blocking to avoid deadlocks or delays in stopping tasks.
When NOT to use
Preempting is not suitable for very short or atomic tasks that finish instantly; simple service calls or topics are better. Also, if tasks cannot be safely interrupted, preempting should be avoided or carefully controlled. Alternatives include designing tasks to be cancelable or using state machines for explicit control.
Production Patterns
In real robots, preempting is used to handle emergency stops, dynamic goal updates, and user overrides. Production systems often combine preempting with safety monitors and layered control to ensure smooth transitions. Complex robots use priority queues and preempt policies to manage multiple simultaneous commands from different sources.
Connections
Interrupt Handling in Operating Systems
Both manage stopping or pausing ongoing processes to handle higher priority tasks.
Understanding OS interrupts helps grasp how preempting allows a system to respond quickly to urgent events without waiting for current tasks to finish.
Real-Time Systems Scheduling
Preempting actions in ROS relate to scheduling tasks with priorities and preemption in real-time systems.
Knowing real-time scheduling principles clarifies why preempting must be cooperative and carefully managed to maintain system stability.
Customer Service Call Transfers
Preempting is like transferring a call to a more urgent or specialized agent before the current call finishes.
This analogy shows how tasks can be interrupted and replaced smoothly to improve responsiveness and service quality.
Common Pitfalls
#1Server ignores preempt requests and keeps running the old task.
Wrong approach:void executeCB(const GoalConstPtr& goal) { // No preempt check while (task_not_done) { // do work } setSucceeded(); }
Correct approach:void executeCB(const GoalConstPtr& goal) { while (task_not_done) { if (as.isPreemptRequested() || !ros::ok()) { setPreempted(); return; } // do work } setSucceeded(); }
Root cause:Misunderstanding that preempting requires explicit checks in server code.
#2Client cancels goal when intending to replace it with a new one.
Wrong approach:client.cancelGoal(); client.sendGoal(new_goal);
Correct approach:client.sendGoal(new_goal); // This preempts the old goal automatically
Root cause:Confusing canceling with preempting leads to unintended task stopping.
#3Preempt callback blocks or takes too long, causing delays.
Wrong approach:void preemptCB() { // Long blocking operation sleep(5); setPreempted(); }
Correct approach:void preemptCB() { // Quick flag set preempt_requested = true; setPreempted(); }
Root cause:Not realizing preempt handlers must be fast and non-blocking to keep system responsive.
Key Takeaways
Preempting actions in ROS allow robots to stop or replace ongoing tasks quickly and safely.
Preempting is cooperative; servers must explicitly check and handle preempt requests in their code.
Clients preempt by sending new goals or canceling current ones, controlling robot behavior dynamically.
Proper preempt handling prevents unsafe states and improves robot responsiveness in changing environments.
Advanced preempting involves managing multiple requests and ensuring thread-safe, non-blocking callbacks.

Practice

(1/5)
1.

What does cancel_goal() do in ROS action clients?

easy
A. It requests to stop the currently running action goal.
B. It starts a new action goal immediately.
C. It pauses the action without stopping it.
D. It resets the action server to its initial state.

Solution

  1. Step 1: Understand the purpose of cancel_goal()

    This function is used to request the cancellation of the current goal being processed by the action server.
  2. Step 2: Differentiate from other actions

    Starting a new goal or pausing are different operations; cancel_goal() specifically requests stopping the current goal.
  3. Final Answer:

    It requests to stop the currently running action goal. -> Option A
  4. Quick Check:

    cancel_goal() stops current goal [OK]
Hint: Remember: cancel_goal() means stop current action [OK]
Common Mistakes:
  • Confusing cancel_goal() with starting a new goal
  • Thinking cancel_goal() pauses instead of cancels
  • Assuming cancel_goal() resets the server
2.

Which of the following is the correct sequence to preempt an action in ROS?

1. cancel_goal()
2. send_goal(new_goal)
easy
A. Call cancel_goal() first, then send_goal(new_goal).
B. Call send_goal(new_goal) first, then cancel_goal().
C. Call cancel_goal() twice, then send_goal(new_goal).
D. Only call send_goal(new_goal) without canceling.

Solution

  1. Step 1: Understand preempting order

    You must first cancel the current goal to stop it before sending a new goal to replace it.
  2. Step 2: Confirm correct method calls

    Calling cancel_goal() first ensures the old task stops, then send_goal(new_goal) starts the new task.
  3. Final Answer:

    Call cancel_goal() first, then send_goal(new_goal). -> Option A
  4. Quick Check:

    Cancel before sending new goal [OK]
Hint: Cancel first, then send new goal to preempt [OK]
Common Mistakes:
  • Sending new goal before canceling old one
  • Calling cancel_goal() multiple times unnecessarily
  • Skipping cancel_goal() and sending new goal directly
3.

Given this ROS action client code snippet, what will be the output behavior?

client.send_goal(goal1)
client.cancel_goal()
client.send_goal(goal2)

What happens to goal1 and goal2?

medium
A. Neither goal runs because cancel_goal() stops all actions.
B. goal1 runs fully; goal2 is ignored.
C. Both goal1 and goal2 run simultaneously.
D. goal1 is canceled; goal2 starts running.

Solution

  1. Step 1: Analyze the cancel_goal() effect

    After sending goal1, cancel_goal() requests to stop it immediately.
  2. Step 2: Understand sending goal2

    Sending goal2 after canceling goal1 starts the new action goal.
  3. Final Answer:

    goal1 is canceled; goal2 starts running. -> Option D
  4. Quick Check:

    Cancel old goal, start new goal [OK]
Hint: Cancel stops old goal; new send_goal starts new task [OK]
Common Mistakes:
  • Assuming goal1 runs fully despite cancel
  • Thinking both goals run at once
  • Believing cancel_goal() stops all future goals
4.

Identify the error in this ROS action client code snippet:

client.send_goal(goal1)
client.send_goal(goal2)
client.cancel_goal()

What is wrong with this sequence?

medium
A. The code should call cancel_goal() twice to cancel both goals.
B. You cannot send two goals without canceling the first one first.
C. Calling cancel_goal() after sending two goals does not preempt correctly.
D. There is no error; this sequence is correct.

Solution

  1. Step 1: Understand goal handling

    Sending two goals in a row without canceling means the second goal overrides the first immediately.
  2. Step 2: Analyze cancel_goal() timing

    Calling cancel_goal() after both sends only cancels the currently active goal, not preempting properly between goals.
  3. Final Answer:

    Calling cancel_goal() after sending two goals does not preempt correctly. -> Option C
  4. Quick Check:

    Cancel before sending new goal to preempt [OK]
Hint: Cancel before sending next goal, not after [OK]
Common Mistakes:
  • Sending multiple goals without canceling first
  • Assuming cancel_goal() cancels all previous goals
  • Calling cancel_goal() too late to preempt
5.

You want to preempt a running action only if it has been active for more than 5 seconds. Which approach correctly implements this logic?

if client.get_state() == ACTIVE and client.get_time_active() > 5:
    client.cancel_goal()
    client.send_goal(new_goal)
hard
A. You must call cancel_goal() before checking the state.
B. This approach correctly preempts only after 5 seconds of activity.
C. You should send the new goal first, then cancel the old one.
D. ROS actions do not support checking active time for preemption.

Solution

  1. Step 1: Check action state and duration

    The code checks if the action is active and has been running longer than 5 seconds.
  2. Step 2: Cancel and send new goal conditionally

    Only if both conditions are true, it cancels the current goal and sends a new one, correctly preempting.
  3. Final Answer:

    This approach correctly preempts only after 5 seconds of activity. -> Option B
  4. Quick Check:

    Check state and time before canceling [OK]
Hint: Check active state and time before canceling [OK]
Common Mistakes:
  • Canceling without checking active time
  • Sending new goal before canceling old one
  • Assuming ROS lacks timing info for actions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard