Ask coding questions

← Back to all posts
How do you run a constant loop in the background in Python?
PikachuB2005 (7)

I want this to run all the time, not just when it receives an event from something else.

Answered by Coder100 (17091) [earned 5 cycles]
View Answer
Coder100 (17091)
from threading import Thread

def constant_loop():
  while True:
    # do something

def main():
  # do something

a = Thread(target=constant_loop)
b = Thread(target=main)
Coder100 (17091)

mark as correct answer please @BrandenBentley

PikachuB2005 (7)

@Coder100 Forgot about this... but now I have a few questions.
1. Can I run a loop that has been imported
2. Do I have do define it as a variable, because I'd rather not
ex. Thread(target=main).run()

Coder100 (17091)
  1. yeah ofc
  2. yeah there's something called lambdas @BrandenBentley
PikachuB2005 (7)

Whenever I need help my first options will be you and IntellectualGuy. It seems like everything I don't know is simple, I just need someone to explain it to me first.

PikachuB2005 (7)

@Coder100 There seems to be a delay using this... what about multiprocessing?

Coder100 (17091)

use multiple threads.