如何在线程中运行Python程序的start函数
如何将Python程序中的start函数放在线程中运行?
你的原代码中start()是阻塞式函数(死循环+sleep),直接调用会导致主程序无法继续执行。通过Python标准库的threading模块,我们可以把它放到独立线程中运行,实现并发执行。
改进后的完整代码
import time import threading jobs = [] verbose = False def initialize(ver): global verbose verbose = ver def addJob(function, timeout, args=None): global verbose """ Adds job to the cron list :param function: Function to call :param timeout: Call after every x seconds """ jobs.append([function, timeout, args]) if verbose: print("Cron Job [ {0}('{1}') ] Registered [Running Every {2}s]".format(function.__name__, args, timeout)) def start(): """ Start the cron job counter This is a thread-blocking function """ seconds = 1 while True: for job in jobs: if seconds % job[1] == 0: if job[2] is None: job[0]() else: job[0](job[2]) time.sleep(1) seconds += 1 def run_in_thread(): """ Creates a new thread and starts the cron job counter in that thread """ thread = threading.Thread(target=start) thread.start() # 示例用法 initialize(True) def my_function(): print("Running cron job") addJob(my_function, 5) # 添加每5秒运行一次的任务 # 在独立线程中启动定时任务 run_in_thread() # 主程序可以继续执行其他逻辑,不会被阻塞 print("主程序继续运行...")
关键改动说明
- 引入threading模块:Python内置的多线程工具,无需额外安装
- 新增run_in_thread函数:封装线程创建与启动逻辑,通过
threading.Thread(target=start)指定要在新线程中执行的start函数,调用thread.start()启动线程 - 规范写法优化:将原代码中的
while 1改为更清晰的while True,== None改为Python推荐的is None - 非阻塞效果:启动线程后,主程序不会被
start的死循环卡住,可以继续执行后续代码
内容的提问来源于stack exchange,提问作者disease
相关产品推荐
相关产品推荐

