Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workflows を起動する

最終更新 Markdown で表示Agent セットアップ

Workflows は、プログラムからも Workflows API からも起動できます。次を含みます。

  1. Workers から、fetch ハンドラーの HTTP リクエスト、または queue / scheduled ハンドラーのバインディング経由
  2. Wrangler 設定の Workflow バインディングで schedules を定義し、定期的な間隔で
  3. Workflows REST API を使う
  4. ターミナルの wrangler CLI 経由

Workers API(バインディング)

Worker スクリプトから、Workflow へのバインディングを作り、プログラムで Workflows とやり取りできます。Worker は複数の Workflows にバインドできます。アカウント内のほかの Workers プロジェクト(スクリプト)で定義した Workflows も含みます。

Workflow は次の方法で起動できます。

  • fetch ハンドラー経由で HTTP から直接
  • queue ハンドラー内の Queue コンシューマー から
  • wrangler.jsonc の Workflow バインディングで schedules を定義し、定期スケジュールで
  • scheduled ハンドラー内の Cron Trigger から
  • Durable Object 内から

Workers コードから Workflow にバインドするには、特定の Workflow への バインディング を定義します。たとえば、はじめにガイド で定義した Workflow にバインドするには、Wrangler 設定ファイル を次のように設定します。

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "workflows-tutorial",
	"main": "src/index.ts",
	// Set this to today's date
	"compatibility_date": "2026-09-20",
	"workflows": [
		{
			// The name of the Workflow
			"name": "workflows-tutorial",
			// The binding name, which must be a valid JavaScript variable name.  This will
			// be how you call (run) your Workflow from your other Workers handlers or
			// scripts.
			"binding": "MY_WORKFLOW",
			// Must match the class defined in your code that extends the Workflow class
			"class_name": "MyWorkflow"
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "workflows-tutorial"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-09-20"

[[workflows]]
name = "workflows-tutorial"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"

binding = "MY_WORKFLOW" の行は、Workflow メソッドにアクセスする JavaScript 変数を定義します。create(新しいインスタンスを起動)や get(既存インスタンスのステータスを返す)を含みます。

Workflow を直接スケジュールする

定期的な間隔で Workflow インスタンスを作成したい場合は、Wrangler 設定の Workflow バインディングに schedules 配列(アカウントあたり最大 100 の cron 式)を追加します。

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "workflows-tutorial",
	"main": "src/index.ts",
	// Set this to today's date
	"compatibility_date": "2026-09-20",
	"workflows": [
		{
			"name": "workflows-tutorial",
			"binding": "MY_WORKFLOW",
			"class_name": "MyWorkflow",
			"schedules": ["0 * * * *"]
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "workflows-tutorial"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-09-20"

[[workflows]]
name = "workflows-tutorial"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"
schedules = [ "0 * * * *" ]

一致する各 cron 式は、新しい Workflow インスタンスを自動作成します。トップレベルの triggers.crons と別の scheduled ハンドラーを定義せずに、スケジュールで Workflow を動かしたいときに使います。

スケジュールされたインスタンスは、一致した cron 式とスケジュールされたトリガー時刻を event.schedule に持ちます。

export class MyWorkflow extends WorkflowEntrypoint<Env> {
	async run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
		if (event.schedule) {
			console.log(event.schedule.cron);
			console.log(new Date(event.schedule.scheduledTime));
		}
	}
}

Workers Paid では、schedules が作成した Workflow インスタンスは、cron 1 回あたり最大 1 時間、Workflow の同時実行スロットを消費せずに実行できます。その時間窓のあとにインスタンスが一時停止またはスリープすると、インスタンスは譲り、再開時に通常の同時実行キューに入ります。同時実行スロットが空くと再開します。

Workflow のスケジュールを設定するときは、最新の Wrangler リリースを使います。ローカルの Wrangler スキーマがまだ schedules を認識しない場合は、デプロイ前に Wrangler を更新します。

次の例は、Worker 内から Workflows を管理する方法です。次を含みます。

  • ID で既存 Workflow インスタンスのステータスを取得する
  • 新しい Workflow インスタンスを作成(起動)する
  • 指定したインスタンス ID のステータスを返す
src/index.tsts
interface Env {
	MY_WORKFLOW: Workflow;
}

export default {
	async fetch(req: Request, env: Env) {
		// Get instanceId from query parameters
		const instanceId = new URL(req.url).searchParams.get("instanceId");

		// If an ?instanceId=<id> query parameter is provided, fetch the status
		// of an existing Workflow by its ID.
		if (instanceId) {
			let instance = await env.MY_WORKFLOW.get(instanceId);
			return Response.json({
				status: await instance.status(),
			});
		}

		// Else, create a new instance of our Workflow, passing in any (optional)
		// params and return the ID.
		const newId = crypto.randomUUID();
		let instance = await env.MY_WORKFLOW.create({ id: newId });
		return Response.json({
			id: instance.id,
			details: await instance.status(),
		});
	},
};

Workflow のステータスを確認する

特定のインスタンス ID に対して status を呼び、実行中の任意の Workflow インスタンスのステータスを確認できます。インスタンスがキュー待ち(スケジュール待ち)、実行中、一時停止、エラーのいずれかをプログラムで確認できます。

let instance = await env.MY_WORKFLOW.get("abc-123");
let status = await instance.status(); // Returns an InstanceStatus

status の取りうる値は次のとおりです。

  status:
    | "queued" // means that instance is waiting to be started (see concurrency limits)
    | "running"
    | "paused"
    | "errored"
    | "terminated" // user terminated the instance while it was running
    | "complete"
    | "waiting" // instance is hibernating and waiting for sleep or event to finish
    | "waitingForPause" // instance is finishing the current work to pause
    | "unknown";
  error?: {
    name: string,
    message: string
  };
	output?: unknown;
	rollback:
		| {
				outcome: "complete" | "failed";
				error: {
					name: string,
					message: string,
				} | null,
		  }
		| null;

step.do() にロールバックハンドラーを登録している場合、インスタンス終了後に rollback を確認し、補償ステップが成功したかを見ます。ロールバックが実行中のあいだ、Workers API は status: "running" を返し続けます。

ポーリングなしで過去とライブの実行更新を受け取る方法は、イベントの購読 を参照してください。

Workflow を明示的に一時停止する

特定のインスタンス ID に対して pause を呼び、Workflow インスタンスを明示的に一時停止できます(あとで再開できます)。

let instance = await env.MY_WORKFLOW.get("abc-123");
await instance.pause(); // Returns Promise<void>

Workflow を再開する

特定のインスタンス ID に対して resume を呼び、一時停止した Workflow インスタンスを再開できます。

let instance = await env.MY_WORKFLOW.get("abc-123");
await instance.resume(); // Returns Promise<void>

現在一時停止していないインスタンスに resume を呼んでも効果はありません。

Workflow を停止する

特定のインスタンス ID に対して terminate を呼び、Workflow インスタンスを停止 / 終了できます。

let instance = await env.MY_WORKFLOW.get("abc-123");
await instance.terminate(); // Returns Promise<void>

終了前に登録済みロールバックハンドラーを実行するには、rollback: true を渡します。

let instance = await env.MY_WORKFLOW.get("abc-123");
await instance.terminate({ rollback: true }); // Returns Promise<void>

Wrangler からロールバックハンドラーを実行することもできます。

npx wrangler workflows instances terminate <WORKFLOW_NAME> <INSTANCE_ID> --rollback
# For a local Workflows instance during wrangler dev:
npx wrangler workflows instances terminate <WORKFLOW_NAME> <INSTANCE_ID> --local --rollback

停止 / 終了した Workflow インスタンスは再開 できません

Workflow を再起動する

let instance = await env.MY_WORKFLOW.get("abc-123");
await instance.restart(); // Returns Promise<void>

インスタンスを再起動すると、進行中のステップはすぐにキャンセルされ、中間状態は消去され、Workflow は初めて実行されたかのように扱われます。

先頭ではなく特定ステップからインスタンスを再起動するには、Workers API リファレンスの restart を参照してください。

Workflow インスタンスを削除する

インスタンスを削除すると、保存された状態が消えます。実行中のインスタンスを削除すると、ロールバックハンドラーを実行せずに現在の実行を止めます。

ハンドルの delete() を呼び、1 つのインスタンスを削除します。

const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();
const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();

Workflow が自身のインスタンスを削除すると、await instance.delete() のあいだに実行が止まります。その呼び出しのあとのコードは動きません。

deleteBatch() で、1 回の呼び出しで最大 100 インスタンスを削除できます。

const result = await env.MY_WORKFLOW.deleteBatch([
	"instance-abc",
	"instance-def",
]);

console.log(result.deleted); // [{ id: "instance-abc" }, { id: "instance-def" }]
console.log(result.errors); // Per-instance failures, if any
const result = await env.MY_WORKFLOW.deleteBatch([
	"instance-abc",
	"instance-def",
]);

console.log(result.deleted); // [{ id: "instance-abc" }, { id: "instance-def" }]
console.log(result.errors); // Per-instance failures, if any

deleteBatch() は 1〜100 個の ID を受け付けます。存在しない ID はインスタンスごとのエラーとして返ります。重複 ID は上限に数えられ、1 回だけ削除され、各入力位置に結果が繰り返されます。いずれかの ID が無効な場合、どのインスタンスも削除せずに呼び出しは失敗します。

Wrangler は、1 つ以上のインスタンス ID、または文字列のトップレベル JSON 配列を含むファイルを受け付けます。位置指定の ID と --filename を組み合わせられ、合計 100 ID までです。最も最近作成したインスタンスを削除するには latest を使います。

instance-ids.jsonjson
["instance-abc", "instance-def"]
npx wrangler workflows instances delete <WORKFLOW_NAME> <INSTANCE_ID>
npx wrangler workflows instances delete <WORKFLOW_NAME> <INSTANCE_ID> <INSTANCE_ID>
npx wrangler workflows instances delete <WORKFLOW_NAME> latest
npx wrangler workflows instances delete <WORKFLOW_NAME> --filename ./instance-ids.json
# For local Workflow instances during wrangler dev:
npx wrangler workflows instances delete <WORKFLOW_NAME> <INSTANCE_ID> --local

API の全体は deletedeleteBatch を参照してください。

別の Workflow から Workflow を起動する

別の Workflow のステップ内から、新しい Workflow インスタンスを作成できます。親 Workflow は、子 Workflow の完了を待ってブロックしません。子インスタンスの作成が成功すると、すぐに実行を続けます。

export class ParentWorkflow extends WorkflowEntrypoint {
	async run(event, step) {
		// Perform initial work
		const result = await step.do("initial processing", async () => {
			// ... processing logic
			return { fileKey: "output.pdf" };
		});

		// Trigger a child workflow for additional processing
		const childInstance = await step.do("trigger child workflow", async () => {
			return await this.env.CHILD_WORKFLOW.create({
				id: `child-${event.instanceId}`,
				params: { fileKey: result.fileKey },
			});
		});

		// Parent continues immediately - not blocked by child workflow
		await step.do("continue with other work", async () => {
			console.log(`Started child workflow: ${childInstance.id}`);
			// This runs right away, regardless of child workflow status
		});
	}
}
export class ParentWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		// Perform initial work
		const result = await step.do("initial processing", async () => {
			// ... processing logic
			return { fileKey: "output.pdf" };
		});

		// Trigger a child workflow for additional processing
		const childInstance = await step.do("trigger child workflow", async () => {
			return await this.env.CHILD_WORKFLOW.create({
				id: `child-${event.instanceId}`,
				params: { fileKey: result.fileKey },
			});
		});

		// Parent continues immediately - not blocked by child workflow
		await step.do("continue with other work", async () => {
			console.log(`Started child workflow: ${childInstance.id}`);
			// This runs right away, regardless of child workflow status
		});
	}
}

子 Workflow の起動に失敗すると、ステップは失敗し、再試行設定に従って再試行されます。子インスタンスの作成が成功すると、親から独立して実行されます。

REST API(HTTP)

Workflows REST API ドキュメント を参照してください。

コマンドライン(CLI)

コマンドラインから Workflows を管理・起動する方法は、CLI クイックスタート を参照してください。

役に立ちましたか?