2

Apologies for my poor phrasing but here goes.

I need to execute a function every thirty minutes whilst other tasks are running however I have no idea how to do this or to phrase it into google. My goal is to modify my script so that it operates (without a UI) like the task manager program with background services, programs, utils, ect.

I have tried to create this by timing each function and creating functions that execute other functions however no matter what I try it operates in an asynchronous fashion like any script would.

An example of this would include the following.

def function_1():
    """Perform operations"""
    pass

def function_2():
    """Perform operations"""
    pass

def executeAllFunctions():
    function_1()
    function_2()

How can I initialize function_1 as a background task whilst function_2 is executed in a normal manner?

Yunus Temurlenk
  • 4,085
  • 4
  • 18
  • 39

1 Answers1

1

There is an excellent answer here. The main idea is to run an async coroutine in a forever loop inside a thread.

In your case, you have to define function one as a coroutine use a caller function to be in the thread and create a thread.

Sample example heavily inspired to the answer in the link but adapted to your question.

@asyncio.coroutine
def function_1():
    while True:
       do_stuff
       yield from asyncio.sleep(1800)

def wrapper(loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(function_1())

def function_2():
    do_stuff


def launch():
    loop = asyncio.get_event_loop()  
    t = threading.Thread(target=wrapper, args=(loop,))  # create the thread
    t.start()  # launch the thread

    function_2()
    t.exit() # when function_2 return
RomainL.
  • 997
  • 1
  • 10
  • 24