跳转到内容
搜索文档

状态钩子

响应 Container 状态变化执行 Workers 代码

最后更新 查看 MarkdownAgent 设置

当 Container 启动、停止、变为空闲和出错时,它可以触发在 Container 类上定义了状态钩子的 Worker 中的代码执行。有关更多详细信息,请参阅 Container class lifecycle hooks

import { Container } from "@cloudflare/containers";

export class MyContainer extends Container {
	defaultPort = 4000;
	sleepAfter = "5m";

	override onStart() {
		console.log("Container successfully started");
	}

	override onStop(stopParams) {
		if (stopParams.exitCode === 0) {
			console.log("Container stopped gracefully");
		} else {
			console.log("Container stopped with exit code:", stopParams.exitCode);
		}

		console.log("Container stop reason:", stopParams.reason);
	}

	override async onActivityExpired() {
		console.log("Container became idle, stopping it now");
		await this.stop();
	}

	override onError(error: string) {
		console.log("Container error:", error);
	}
}

这篇文档对您有帮助吗?