How to loop a function with two different intervals?
I want the 1st instance running every 3 seconds and the 2nd instance running every 6 seconds
import time
def test(name, frequency):
while True:
print(name)
time.sleep(frequency)
But it only runs the first function, I want them running in the same time but two different intervals (3seconds and 6 seconds)
test("one", frequency=3)
test("two", frequency=6)
Thank you!
CodePudding user response:
If you only need to do it for 3 and 6 second intervals, you could get away with not using threading or multiprocessing by skipping the 6 second interval function for every odd iteration.
import time
counter = 0
while True:
if counter%2 == 0:
# 6 second interval function
print("6 second function")
# 3 second interval function
print("3 second function")
counter = 1
time.sleep(3)
Note that your 3 second interval might not actually be 3 seconds, it will be 3 seconds plus however long it takes to execute your function
CodePudding user response:
As Pedro Maia commented, python naturally can't make simultaneous stuff. So you need a multiprocessing module. For instance you can make a dictionary with the name and frequencies to use and access that dictionary by processes to join. Using the multiprocessing library (comes in the standard library) you can use the multiprocessing.Process(target=function name,args=[arg1,arg2...]) function. Each multiprocess will be assigned a different part of your pc (roughly speaking) to achieve or run the task. When you call the processes with start() you can run parallel tasks, and then you must call join() on them, thats where the script will run on a single process again. You may need to add an innate "stopper" to your function (that stops the while loop) since the multiprocessing may become blind to counters outside the function.
For instance:
import time
def test(name, frequency):
k=0
while k<500:
print(name)
k =1
time.sleep(frequency)
a=multiprocessing.Process(target=test,args=["one",3])
b=multiprocessing.Process(target=test,args=["two",6])
a.start()
b.start()
a.join()
b.join()
This is an oversimplification and it may be useful to look for a youtube multiprocessing tutorial.
CodePudding user response:
Sounds like you want to know how to multithread. Having multiple threads allows you to do multiple things at once.
The link shows you how to multithread in python.
CodePudding user response:
Thanks for all the tips here is what I find that works
t1 = threading.Thread(target=test, args=("one", 3))
t2 = threading.Thread(target=test, args=("two", 6))
t1.start()
t2.start()
t1.join()
t2.join()