如果在特定时间后 FastAPI 中没有输入请求,则停止 AWS EC2

Stop AWS EC2 if no input requests in FastAPI after a specific time

我有 AWS EC2 Windows 服务器,我在 uvicorn 上 运行 FastAPI。例如,如果 FastAPI 中没有来自客户端的输入请求,是否有关闭 Windows 服务器的好方法? 30分钟? 我正在使用 Python 3.9.7.

您可以在 FastAPI 服务器上次发出请求时附加到文件。然后,使用 cronjob 或类似工具,您可以检查文件的最后一行,将该时间与当前时间进行比较,并在需要时关闭服务器。无论如何,这都是一种骇人听闻的解决方案,因为它会在不进行任何准备工作的情况下停止服务器。

示例:

FastAPI 代码

from fastapi import FastAPI
from time import time

app = FastAPI()

def save_req_time():
    with open("./req_time.txt", "a") as fle:
        fle.write(f"{time()}\n")


@app.get("/")
async def root():
   save_req_time()
   return {"message": "Hello World"}

关机脚本(Powershell) 此脚本读取上次请求时间,检查时间增量,并在必要时关闭服务器。

Windows server shutdown command docs

$current_time = [int64](Get-Date -UFormat %s)

Get-Content .\req_time.txt -Tail 1 -Wait | ForEach-Object {

    If ([int64]($_) - $current_time -ge 1800) { 

        shutdown
    
    }

}

安排关机作业(powershell) 在这里,您将关闭脚本安排为每分钟 运行。

Windows scheduled task docs

$action = New-ScheduledTaskAction -Execute './shutdown_script.ps1'
$trigger = New-ScheduledTaskTrigger `
     -Daily -At 0am `
     -RepetitionInterval (New-TimeSpan -Minutes 1) `
     -RepetitionDuration (New-TimeSpan -Days 1)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "shutdown_fastapi"

对于更专业(但复杂)的解决方案,您可以查看此 python 库:RQ 安排后台作业,这些作业可以进行此处建议的检查,避免使用 powershell 脚本和任务调度程序。