... | ... | @@ -249,4 +249,76 @@ What you with this code is on your own. |
|
|
|
|
|
# Stop handler
|
|
|
|
|
|
We saw before that there was a difference between a *stop* and a *kill* request. The Cameo server immediately stops the app for a *kill* request whereas in case of a *stop* request it sets the state *STOPPING* to the app. The app receives the *STOPPING* event and a stop handler is triggered if it has been registered allowing to properly terminate the app.
|
|
|
|
|
|
The C++, Java and Python APIs support the stop handler. An example in C++:
|
|
|
```cpp
|
|
|
#include <cameo/api/cameo.h>
|
|
|
#include <atomic>
|
|
|
#include <iostream>
|
|
|
|
|
|
// Shared variable.
|
|
|
std::atomic_bool stopping(false);
|
|
|
|
|
|
int main(int argc, char *argv[]) {
|
|
|
|
|
|
// Init the app.
|
|
|
cameo::application::This::init(argc, argv);
|
|
|
|
|
|
// Define a stop handler.
|
|
|
cameo::application::This::handleStop([] {
|
|
|
std::cout << "Stop handler executed" << std::endl;
|
|
|
});
|
|
|
|
|
|
// Loop until stop is triggered.
|
|
|
while (!stopping.load()) {
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
|
|
}
|
|
|
|
|
|
return 0;
|
|
|
}
|
|
|
```
|
|
|
|
|
|
This example uses an *std::atomic_bool* variable to stop the while loop.
|
|
|
|
|
|
An example in Java:
|
|
|
```java
|
|
|
import fr.ill.ics.cameo.base.This;
|
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
|
|
|
|
|
public class JavaStop {
|
|
|
|
|
|
// Shared variable.
|
|
|
public static AtomicBoolean stopping = new AtomicBoolean(false);
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
|
// Init the app.
|
|
|
This.init(args);
|
|
|
|
|
|
// Define a stop handler.
|
|
|
This.handleStop(() -> {
|
|
|
System.out.println("Stop handler executed");
|
|
|
stopping.set(true);
|
|
|
});
|
|
|
|
|
|
// Loop until stop is triggered.
|
|
|
while (!stopping.get()) {
|
|
|
try {
|
|
|
Thread.sleep(100);
|
|
|
}
|
|
|
catch (InterruptedException e) {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
This.terminate();
|
|
|
}
|
|
|
}
|
|
|
```
|
|
|
|
|
|
This example also uses an *AtomicBoolean* variable to stop the while loop.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
WARNING: USE STOP HANDLER FOR canceling blocking calls, etc. |