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

使用ProcessPoolExecutor并行运行含schedule的两函数问题求助

解决方案

问题原因分析

  1. Windows多进程环境下的模块导入问题:如果没有if __name__ == '__main__'入口保护,Windows系统创建子进程时会重新导入主模块,导致代码重复执行、进程启动异常,表现为仅单个函数运行。
  2. 线程环境下的全局调度器冲突:schedule模块默认使用全局调度器,多线程共享同一调度器会导致任务执行混乱,甚至出现单个线程阻塞的情况。

多进程修复方案

添加主入口保护,并确保进程池足够容纳两个任务:

import time
import schedule
from concurrent.futures import ProcessPoolExecutor

def job1():
    print("Job 1 executed")

def job2():
    print("Job 2 executed")

def func1():
    schedule.every().minute.at(":10").until("23:00").do(job1)
    while True:
        schedule.run_pending()
        time.sleep(1)

def func2():
    schedule.every().minute.at(":10").until("23:00").do(job2)
    while True:
        schedule.run_pending()
        time.sleep(1)

def func3():
    # 指定max_workers=2确保两个进程能同时启动
    with ProcessPoolExecutor(max_workers=2) as executor:
        executor.submit(func1)
        executor.submit(func2)

# Windows下必须添加该入口保护,避免子进程重复执行代码
if __name__ == '__main__':
    func3()

多线程修复方案

为每个线程创建独立的schedule.Scheduler实例,避免全局调度器冲突:

import time
import schedule
import threading

def job1():
    print("Job 1 executed")

def job2():
    print("Job 2 executed")

def func1():
    # 创建独立的调度器实例
    s1 = schedule.Scheduler()
    s1.every().minute.at(":10").until("23:00").do(job1)
    while True:
        s1.run_pending()
        time.sleep(1)

def func2():
    # 创建独立的调度器实例
    s2 = schedule.Scheduler()
    s2.every().minute.at(":10").until("23:00").do(job2)
    while True:
        s2.run_pending()
        time.sleep(1)

def func3():
    t1 = threading.Thread(target=func1)
    t2 = threading.Thread(target=func2)
    t1.start()
    t2.start()
    # 等待线程结束(可选,若需主进程保持运行)
    t1.join()
    t2.join()

if __name__ == '__main__':
    func3()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:25:27