I’m new in parallel programming currently needs to run app as a background process which contains several tasks inside. Currently executing only do_something(), it blocks execution of do_something2(). Could please anyone explain me how to implement that? Should I use asyncio or something else? Thank you.
import sched import time import os import subprocess import asyncio event_schedule = sched.scheduler(time.time, time.sleep) def do_something(): print("Hello, World!") ...do my own stuff event_schedule.enter(5, 1, do_something) def do_something2(): print("Hello, World2!") ...do my own stuff here event_schedule.enter(5, 1, do_something2) event_schedule.enter(5, 1, do_something) event_schedule.run() event_schedule.enter(5, 1, do_something2) event_schedule.run()
Advertisement
Answer
I think, however, you need to organize your code as follows so that each process has its own scheduler (I have also modified/rearranged the code so that each process ultimately terminates after some number of iterations for my testing purposes):
import sched import time from multiprocessing import Process def do_something1(): print("Hello, World1!") def scheduler1(): event_schedule = sched.scheduler(time.time, time.sleep) for _ in range(3): event_schedule.enter(5, 1, do_something1) event_schedule.run() def do_something2(): print("Hello, World2!") def scheduler2(): event_schedule = sched.scheduler(time.time, time.sleep) for _ in range(6): event_schedule.enter(5, 1, do_something2) event_schedule.run() if __name__ == '__main__': p1 = Process(target=scheduler1) p1.start() p2 = Process(target=scheduler2) p2.start() p1.join() p2.join()