Python 多线程(while 和 apscheduler)

标签 python multithreading

我试图在 Python 中同时调用两个函数。一种是无限循环,另一种是使用 apscheduler 启动。像这样:

Thread.py

from multiprocessing import Process
import _While
import _Scheduler

if __name__ == '__main__':
    p1 = Process(target=_While.main())
    p1.start()
    p2 = Process(target=_Scheduler.main())
    p2.start()

_While.py

import time


def main():
    while True:
        print "while"
        time.sleep(0.5)

_Scheduler.py

import logging
from apscheduler.scheduler import Scheduler


def _scheduler():
        print "scheduler"


if __name__ == '__main__':
    logging.basicConfig()
    scheduler = Scheduler(standalone=True)
    scheduler.add_interval_job(lambda:  _scheduler(), seconds=2)
    scheduler.start()

由于仅打印了 while ,因此 _Scheduler 似乎尚未启动。 有人可以帮助我吗?

最佳答案

这里至少有几个问题。首先,target 关键字应该是函数,而不是函数的结果。例如:

p1 = Process(target=_While.main)  # Note the lack of function call

其次,我没有看到任何 _Scheduler.main 函数。也许您打算做类似的事情:

import logging
from apscheduler.scheduler import Scheduler


def _scheduler():
        print "scheduler"


def main():
    logging.basicConfig()
    scheduler = Scheduler(standalone=True)
    scheduler.add_interval_job(_scheduler, seconds=2)  # I doubt that `lambda` is necessary here ...
    scheduler.start()

if __name__ == "__main__":
    main()

关于Python 多线程(while 和 apscheduler),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22592092/

相关文章:

python - 在 Python 中将列表的每个元素与另一个列表的每个元素相乘/相加/相除的有效方法

python - 时间增量到 Pandas 数据框中的字符串类型

Python SonarQube 与 Nose 测试和覆盖率集成未显示覆盖代码

c# - 在 C# 中应用程序结束之前计时器不会触发

multithreading - VB6 Timer 控件是否创建单独的线程?

c++ - 在 Managed_shared_memory 中 boost 进程间互斥

python - 创建具有左偏概率分布的随机数

python - 将函数传递给数据框中的列 - Python

c++ - 在 c++0x 中发生了什么以及如何发生

c++ - 为 win32 线程使用不同的静态库内存