“Most services have startup and shutdown workflow-logic which is often sensitive to failure and hard to get right. Startup sequences include actions like initializing thread pools, running data migrations, warming up caches, and other forms of state initialization before taking traffic or accepting events. Shutdown sequences include freeing up resources that hold on to file descriptors or other system resources that may leak if not cleared correctly,” Tom Doron, member of the Swift Core team and Swift Server work group, wrote in a post.
In order to help server apps and frameworks address their own needs, the project provides a safe, reusable, framework-agnostic way of cleanly starting up and shutting down an app.
To get started, the team recommends creating a
ServiceLifecycle instance and register LifecycleTasks with it.
“Upon calling the
ServiceLifecycle will start these tasks in the order they were registered,” Doron wrote. “By default,
ServiceLifecycle also registers a
Signal handler that traps
TERM , which are typical
Signals used in modern deployment platforms to communicate shutdown request. The shutdown sequence begins once the
Signal is captured, and the
LifecycleTasks are shut down in the reverse order they have been registered in.”