0

I have a function that takes a long time to finish. How do I execute another function every X seconds while the long function is executed?

The script is using Python 3.4

Rotareti
  • 49,483
  • 23
  • 112
  • 108
  • 1
    you should have a look into Python's [threading](https://docs.python.org/3.4/library/threading.html#threading.Thread) and/or [multiprocessing](https://docs.python.org/3.4/library/multiprocessing.html). You would need to execute the long taking function in a seperate thread / process. Or you keep the long taking function in the main thread and use a [timer](https://docs.python.org/3.4/library/sched.html) for starating the "other" function every x seconds. – TryToSolveItSimple Jun 08 '16 at 13:31
  • Go through both the dupes, You can do it. – Bhargav Rao Jun 08 '16 at 14:15

1 Answers1

1

Here is a quite simple example. It can still be tuned if important to you to kill the second function when the first function is finished.

import threading, time

def func_long(ev):
    # do stuff here
    for _ in range(12):
        print("Long func still working")
        time.sleep(1)

    # if complete
    ev.set()

def run_func(ev, nsec):
    if ev.is_set():
        return
    print ("Here run periodical stuff")
    threading.Timer(nsec, run_func, [ev, nsec]).start()

def main():
    ev = threading.Event()
    threading.Timer(5.0, run_func, [ev, 5]).start()
    func_long(ev)

if __name__=='__main__':
    main()
quantummind
  • 2,086
  • 1
  • 14
  • 20