How to Auto-Restart a Crashed Application Without Restarting io.Connect Desktop

Question

A background application running within io.Connect Desktop stopped unexpectedly - how to auto-restart without restarting the platform?

Answer

io.Connect 9.x stream

Use the onInstanceStopped method on the application object to detect when an instance stops, then call start() to restart it. The code below:

  1. Retrieves the application object by name from the App Manager.
  2. Subscribes to the onInstanceStopped event for that specific application.
  3. When the instance stops (for any reason), waits 10 seconds and then starts a new instance.
const myApp = io.appManager.application("my-app");

if (!myApp) {
    console.error("App is not available in the App Manager");
    return;
}

myApp.onInstanceStopped((instance) => {
    console.error("App instance stopped", instance.id);

    setTimeout(() => {
        console.warn("Restarting app instance");
        myApp.start();
    }, 10_000);
});

io.Connect Desktop 10.0+

io.Connect Desktop 10.0 introduced the new Apps API (io.apps). The new API provides an onStopped method with an InstanceStoppedEvent object that includes a reason property:

const handler = async ({ instance, reason }) => {
    console.warn(`App instance ${instance.id} stopped. Reason: ${reason}`);

    setTimeout(async () => {
        console.warn("Restarting app instance");
        await io.apps.instances.start({ name: "my-app" });
    }, 10_000);
};

const unsubscribe = io.apps.instances.onStopped(handler);

The reason property provides information about why the instance stopped, which you may be able to use to decide whether a restart is appropriate.

Note: The new Apps API is marked as experimental and is disabled by default. To enable it, set the apps property to true in the configuration object when initializing the @interopio/desktop library.

Related Documentation