简体   繁体   中英

How can I make a function run in the background without blocking my entire program?

I have some difficulties into making this function running in the background without blocking my entire program, how can I run that function in loop, without blocking my entire program? This is the function: while True: schedule.run_pending()

Thank you for any reply.

Edit:

def FunctioninLoop():
    while True:
        schedule.run_pending()

async def MyFunction():
    ScheduleToexecute=schedule.every().minute.do(Functionscheduled)
    t = Thread(target=FunctioninLoop())
    t.start()
    print("The execution is going on")

Threads are what you are looking for. Consider the following code:

from threading import Thread

def myfunc(a, b, c):
    pass

# Creates a thread
t = Thread(target=myfunc, args=(1, 2, 3))

# Launches the thread (while not blocking the main execution)
t.start()

somecode
somecode
somecode

# Waits for the thread to return (not a must)
t.join()

Hope I've helped! :)

import threading
pender = threading.thread(schedule.run_pending) # Does not Block
print("life goes on until...")
pender.join()                 # Blocks until schedule.run_pending() is complete. 

You can use python's subprocess module

https://docs.python.org/3.2/library/subprocess.html

import os

def myfunction():
    ..........


 os.spawnl(os.P_NOWAIT, myfunction())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM