J. Lo
J. Lo

Reputation: 21

How to do periodic tasks in Python

I want to run a function every few seconds in Python. The function execution takes some time, and I want to include that in the waiting time as well.

I don't want to do this, because it is not strictly executed every 2 seconds and will break the periodicity (my_function also takes time to execute.)

while True:
    time.sleep(2)
    my_function()

I don't want to do this neither, because it uses too much CPU on the while loop of Thread-2.

# Thread-1
While True:
    time.sleep(2)
    event.set()

# Thread-2
While True:
    if event.is_set():
        my_function()
    else:
        pass 

Can anyone please help me?

Upvotes: 1

Views: 10612

Answers (3)

i Mr Oli i
i Mr Oli i

Reputation: 755

I found this code works pretty well, if I understood your question correctly.

Code broken down:

  • runs func1
  • runs func2
  • waits 2s
  • does something else after that
  • waits 1s
  • does it all again
import threading
import time

def func1():
    print("function 1 has been called")

def func2():
    print("function 2 has been called")

def loop():
    print("loop print 1")
    thread = threading.Thread(target=func1, name="thread")
    thread.start()

    while thread.is_alive():
        continue

    if not thread.is_alive():
        thread2 = threading.Thread(target=func2, name="thread2")
        thread2.start()

    while thread2.is_alive():
        continue
    
    time.sleep(2)

while True:
    loop()
    print("Some other thing")
    time.sleep(1)

Upvotes: 0

user23952
user23952

Reputation: 682

You can consider ischedule. It takes care of the function execution time right out the box, and doesn't waste CPU time for busy waiting. You can use:

from ischedule import schedule, run_loop

schedule(my_function, interval=2)
run_loop()

Upvotes: 3

Stephen Mason
Stephen Mason

Reputation: 357

I believe the schedule module is your friend

Upvotes: 2

Related Questions