Search code examples
pythontimerbackground

Python timer in background without stopping my code


For school, I am working on a remake of cookie clicker. Basically, every second, I need to add 1 to the players score. I found a way to do this, but my problem is that it will only focus on the timer and then I can't run any other parts of the program as the timer needs to be constantly going. I assume there is some way to make the timer always go on in the background while still running my other code. The way I have the timer setup may not be best (I just researched the timer method and cobbled something together). Here is the code:

x = 1
while x == 1:
     score += 1
     time.sleep(1)

I am still very new and I am kind of learning as I go with this. Thanks!


Solution

  • You have 2 ways. Multithreading/multiprocessing or asyncronous way.

    In first case, you should use multiprocessing or multithreading for start parallel process/thread.

    In second case, you can use event loop and asyncio, to run your functions in asyncronous way.