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

如何在Python中让函数在程序运行期间随机定时执行?

可行,附两种Python实现方案

完全可以实现,核心思路是用多线程或异步协程将定时任务与主程序逻辑分离,确保两者互不阻塞。

方法一:多线程实现(适合同步为主的程序)

通过threading模块启动独立线程处理定时任务,主程序可正常执行其他逻辑:

import threading
import random
import time

def sample_func():
    print("Function is running.")

def scheduled_task():
    while True:
        # 生成5-10分钟的随机间隔(转换为秒)
        interval = random.randint(5*60, 10*60)
        time.sleep(interval)
        sample_func()

# 启动守护线程,主程序结束时自动终止该线程
threading.Thread(target=scheduled_task, daemon=True).start()

# 模拟主程序持续运行的逻辑
while True:
    print("Main program is running...")
    time.sleep(1)

方法二:异步协程实现(适合异步架构的程序)

使用asyncio模块让定时任务与主程序协程并行执行,无需额外线程:

import asyncio
import random

def sample_func():
    print("Function is running.")

async def scheduled_task():
    while True:
        interval = random.randint(5*60, 10*60)
        await asyncio.sleep(interval)
        sample_func()

async def main_program():
    while True:
        print("Main program is running...")
        await asyncio.sleep(1)

async def main():
    # 同时调度主程序和定时任务协程
    await asyncio.gather(main_program(), scheduled_task())

if __name__ == "__main__":
    asyncio.run(main())

注意事项

  • 若sample_func涉及IO操作或资源竞争,需自行添加线程锁(多线程场景)或确保协程安全(异步场景)。
  • 守护线程模式下,主程序退出时定时任务会被强制终止,若需要优雅关闭可自行添加信号处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:24:40