Files
cpp-httplib/docs-src/pages/ja/cookbook/c13-max-timeout.md
yhirose 0fa4912891 Fix broken relative links in cookbook docs (Fix #2490)
Cookbook body links referenced sibling pages with a bare slug
(e.g. `c14-keep-alive`). Under the pretty-URL layout each page lives
in its own directory, so these resolve against the page's own
directory and 404. Prefix them with `../` to match the convention
already used in the tour and llm-app sections.

Verified clean with `docs-gen check`.
2026-07-08 22:45:29 -04:00

1.8 KiB
Raw Blame History

title, order, status
title order status
C13. 全体タイムアウトを設定する 13 draft

C12. タイムアウトを設定するで紹介した3種類のタイムアウトは、いずれも「1回のsendrecv」に対するものです。リクエスト全体の所要時間に上限を設けたい場合は、set_max_timeout()を使います。

基本の使い方

httplib::Client cli("http://localhost:8080");

cli.set_max_timeout(5000); // 5秒ミリ秒単位

auto res = cli.Get("/slow-endpoint");

ミリ秒単位で指定します。接続、送信、受信をすべて含めて、リクエスト全体が指定時間を超えたら打ち切られます。

std::chronoで指定する

こちらもstd::chronoの期間を受け取るオーバーロードがあります。

using namespace std::chrono_literals;
cli.set_max_timeout(5s);

どう使い分けるか

set_read_timeoutは「データが来ない時間」のタイムアウトなので、少しずつデータが流れ続ける状況では発火しません。たとえば1秒ごとに1バイト届くようなエンドポイントは、set_read_timeoutをいくら短くしてもタイムアウトしません。

一方、set_max_timeoutは「経過時間」に対する上限なので、こうしたケースでも確実に止められます。外部APIを叩くときや、ユーザーを待たせすぎたくないときに重宝します。

cli.set_connection_timeout(3s);
cli.set_read_timeout(10s);
cli.set_max_timeout(30s); // 全体で30秒を超えたら中断

Note: set_max_timeout()は通常のタイムアウトと併用できます。短期的な無反応はset_read_timeoutで、長時間の処理はset_max_timeoutで、という二段構えにするのが安全です。