set_time_limit

set_time_limit(int $seconds): bool

重设本脚本的最大执行秒数(从调用起重新计时),0 为不限;超时以致命错误终止脚本。

C C23

C23
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

static void on_alarm(int sig) { (void)sig; /* 真实应用会在此 abort 或 longjmp */ }

int main(void) {
    /* POSIX alarm(2) 是直接前辈:N 秒后送达 SIGALRM */
    signal(SIGALRM, on_alarm);
    unsigned int previous = alarm(120);
    printf("watchdog armed, previous: %u\n", previous);
    unsigned int cancelled = alarm(0); /* 取消;返回剩余秒数 */
    printf("watchdog disarmed, was: %u\n", cancelled);
    return 0;
}
输出
watchdog armed, previous: 0
watchdog disarmed, was: 120

C++ C++26

C++26
#include <csignal>
#include <cstdio>
#include <unistd.h>

static void onAlarm(int) { /* 真实应用会在此 abort 或抛异常 */ }

int main() {
    // 又是 POSIX alarm(2)——C++ 同样没有语言级时限
    std::signal(SIGALRM, onAlarm);
    unsigned int previous = alarm(120);
    std::printf("watchdog armed, previous: %u\n", previous);
    unsigned int cancelled = alarm(0);
    std::printf("watchdog disarmed, was: %u\n", cancelled);
    return 0;
}
输出
watchdog armed, previous: 0
watchdog disarmed, was: 120

C# v11.0.100

v11.0.100
// C#:没有脚本时限;CancellationTokenSource 是惯用的截止时限
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
try {
    await Task.Delay(10, cts.Token);
    Console.WriteLine("work finished within deadline");
} catch (TaskCanceledException) {
    Console.WriteLine("cancelled: timeout");
}
输出
work finished within deadline

Go v1.27.4

v1.27.4
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	// Go:context.WithTimeout 是惯用的截止时限
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	select {
	case <-time.After(10 * time.Millisecond):
		fmt.Println("work finished within deadline")
	case <-ctx.Done():
		fmt.Println("cancelled:", ctx.Err())
	}
}
输出
work finished within deadline

Java v27.0.1

v27.0.1
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Java:没有脚本时限;Future.get(timeout) 给单个任务设界
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> f = pool.submit(() -> {
            Thread.sleep(10);
            return "work finished within deadline";
        });
        try {
            System.out.println(f.get(100, TimeUnit.MILLISECONDS));
        } catch (TimeoutException e) {
            System.out.println("cancelled: timeout");
        } finally {
            pool.shutdownNow();
        }
    }
}
输出
work finished within deadline

JavaScript v26.13.1

v26.13.1
// JS 没有引擎级脚本时限:用 Promise.race 手工做看门狗
let timer;
const watchdog = new Promise((_, reject) => {
  timer = setTimeout(() => reject(new Error("timeout")), 1000);
});
const work = Promise.resolve("work finished within deadline").then((v) => {
  clearTimeout(timer);
  return v;
});
Promise.race([work, watchdog]).then((v) => console.log(v)).catch((e) => console.log(e.message));
输出
work finished within deadline

PHP v8.6.0

v8.6.0
// set_time_limit 限制脚本自身的执行时间;0 表示不限
var_dump(set_time_limit(120));
echo ini_get("max_execution_time"), "\n"; // 回读刚设置的值
set_time_limit(0);
echo ini_get("max_execution_time") === "0" ? "unlimited\n" : "still capped\n";
输出
bool(true)
120
unlimited

Python v3.15.2

v3.15.2
# Python:没有脚本级时限;signal.alarm 是经典的 Unix 看门狗
import signal
signal.alarm(120)  # SIGALRM 将在 120 秒后触发(仅 Unix)
print("watchdog armed for 120s")
signal.alarm(0)    # 解除
print("watchdog disarmed")
输出
watchdog armed for 120s
watchdog disarmed

Rust v1.99.1

v1.99.1
fn main() {
    // Rust 标准库没有超时;tokio 等异步运行时才提供 time::timeout。
    // 纯标准库替代方案:手工检查截止点。
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(100);
    std::thread::sleep(std::time::Duration::from_millis(10)); // 模拟「工作」
    if std::time::Instant::now() < deadline {
        println!("work finished within deadline");
    } else {
        println!("overrun");
    }
}
输出
work finished within deadline

TypeScript v26.13.1

v26.13.1
// TS:同 JS——超时围绕 Promise 手工实现
let timer: ReturnType<typeof setTimeout>;
const watchdog: Promise<never> = new Promise((_, reject) => {
  timer = setTimeout(() => reject(new Error("timeout")), 1000);
});
const work: Promise<string> = Promise.resolve("work finished within deadline").then((v: string) => {
  clearTimeout(timer);
  return v;
});
Promise.race([work, watchdog]).then((v: string) => console.log(v)).catch((e: Error) => console.log(e.message));
输出
work finished within deadline

语言差异说明

C:alarm(2) 是鼻祖——N 秒后送达 SIGALRM,alarm(0) 取消并返回剩余秒数。

C++:同 C,语言层同样没有时限概念。

C#:CancellationTokenSource 是惯用截止时限;Task.Delay(token) 协作取消。

Go:context.WithTimeout 把截止时间挂到调用链上,取消信号随 ctx 传播。

Java:无脚本时限;Future.get(timeout) 给单个任务设界(示例)。

JavaScript:引擎层没有脚本时限;只能围绕 Promise 手工做看门狗,或用 worker 的 terminate。

PHP:只计脚本自身执行时间,sleep/系统调用不计时(Windows 例外,按真实时间计);与 ini_set('max_execution_time') 等价;每次调用计数归零重计;CLI 默认 0 不限。

Python:无内建脚本时限;Unix 下 signal.alarm + SIGALRM 是经典看门狗(仅主线程),或第三方 func_timeout。

Rust:标准库无超时;tokio 的 time::timeout 是异步世界的答案。

TypeScript:同 JavaScript。