Stiletto
Stiletto

Reputation: 65

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

Upvotes: 1

Views: 3532

Answers (3)

Somil
Somil

Reputation: 1941

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

Upvotes: 1

Yoav Godelnik
Yoav Godelnik

Reputation: 71

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! :)

Upvotes: 3

kpie
kpie

Reputation: 11100

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. 

Upvotes: 1

Related Questions