Lennard
Lennard

Reputation: 35

Python Multithreading (while and apscheduler)

I am trying to call two functions simultaneously in Python. One is an infinite loop and the other one is started using apscheduler. Like this:

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()

Since only while is printed it seems that _Scheduler isn’t starting. Can somone help me?

Upvotes: 1

Views: 2433

Answers (1)

mgilson
mgilson

Reputation: 310137

You've got at least a couple problems here. First, the target keyword should be a function, not the result of a function. e.g.:

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

Second, I don't see any _Scheduler.main function. Maybe you meant to do something like:

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()

Upvotes: 3

Related Questions