Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

how to keep a function running in python

  1. User

    how to keep a function running in python

  2. Assistant

    In Python, you can keep a function running continuously using a while loop. Here's an example:

    def my_function():
        # Your function logic here
        print("Running my_function...")
    
    # Keep the function running continuously
    while True:
        my_function()
    

    The above code will run the my_function continuously within a never-ending while loop. Please be careful with this approach, as the function will still run forever until you manually stop the script or your system runs out of resources.

    If you want to run the function continuously with a time delay between each execution, you can use the time.sleep() function from the time module:

    import time
    
    def my_function():
        # Your function logic here
        print("Running my_function...")
    
    # Keep the function running continuously with a time delay
    delay = 5  # Time delay in seconds
    while True:
        my_function()
        time.sleep(delay)
    

    This code will continuously run my_function with a delay of 5 seconds between each execution. You can set the delay value to control the time interval between each execution.