在Python协程/任务中定期执行工作或退出
我刚接触Python,想写一个简单的异步函数,每隔N秒执行一次ps $pid
,直到收到停止信号。也就是说,在Go语言中,这样做就很简单:
go func(cancelCtx context.Context) {
ticker, cancel := time.NewTicker(time.Second)
defer cancel()
looper:
for {
select {
case <-ticker.C:
checkProcess()
case <-ctx.Done():
break looper
}
}
fmt.Println("exited")
}(ctx)
我正在慢慢学习Python的异步编程,但希望能得到一些关于最佳Python写法的指导。谢谢。
1 个回答
0
要同时运行多个任务,你可以使用asyncio模块,配合asyncio.create_task()
来实现类似的功能。
import asyncio
import os
async def check_process(pid):
while True:
# Check if process is still running
if not os.path.exists(f"/proc/{pid}"):
print(f"Process with PID {pid} not found.")
break
else:
print(f"Process with PID {pid} found.")
# Wait for N seconds
await asyncio.sleep(5) # Change 5 to your desired interval
async def main():
pid = 12345 # Replace 12345 with your PID
task = asyncio.create_task(check_process(pid))
await task
if __name__ == "__main__":
asyncio.run(main())