You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现同一函数按两个不同时间间隔并发循环执行

问题原因

你写的顺序调用代码在Python默认单线程同步执行逻辑下,第一个test()函数内部是无限循环,执行后会永远阻塞当前线程,不会走到第二个函数调用步骤,因此只有第一个实例能运行。

实现方案

方案1:多线程实现(改动最小,无需修改原有函数)

直接用Python标准库threading为每个函数实例创建独立线程运行即可:

import time
import threading

def test(name, frequency):
    while True:
        print(name)
        time.sleep(frequency)

# 创建两个线程对象
t1 = threading.Thread(target=test, args=("one", 3))
t2 = threading.Thread(target=test, args=("two", 6))

# 启动线程
t1.start()
t2.start()

# 可选:等待线程执行完成(这里都是无限循环,所以会一直阻塞)
t1.join()
t2.join()

方案2:异步协程实现(资源占用更低,适合大量同类任务)

如果任务是IO密集型,可以用asyncio异步实现,需要将同步sleep替换为异步sleep:

import asyncio

async def test(name, frequency):
    while True:
        print(name)
        await asyncio.sleep(frequency)

async def main():
    # 同时运行两个协程任务
    await asyncio.gather(
        test("one", 3),
        test("two", 6)
    )

asyncio.run(main())

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:06:03