Home > Back-end >  Can I run a coroutine in python independently from all other code?
Can I run a coroutine in python independently from all other code?

Time:10-01

I have a piece of code that I need to be ran every hour. What's the best way to run that piece of code independently from all the other code (It's a telegram bot) without having to refactor everything?(Now I know I can use aiogram for this but I'm using different lib) I'm looking for something like a unity c# coroutine (where you simply StartCoroutine and you have that function ran in parallel), but on python 3.9. I've been searching so much for something not very complicated, that I'll be glad even if this piece of code interrupts my main code while executing, as it takes around 1 second to complete.

CodePudding user response:

You could put your code in a function, then call it using the threading module.

from threading import Thread
from time import sleep

# Here is a function that uses the sleep() function. If you called this directly, it would stop the main Python execution
def my_independent_function():
    print("Starting to sleep...")
    sleep(10)
    print("Finished sleeping.")

# Make a new thread which will run this function
t = Thread(target=my_independent_function)
# Start it in parallel
t.start()

# You can see that we can still execute other code, while other function is running
for i in range(5):
    print(i)
    sleep(1)

And the output:

Starting to sleep...
0
1
2
3
4

Finished sleeping.

As you can see, even while the function was sleeping, the main code execution continued.

  • Related