Search code examples
pythonoperating-systemtaskpython-multithreading

Repeat a task in Python


I'm working on a simple shell program with Python, and I need to repeat a task (a simple os.system call ) every second.

Is it possible to make that, without interrupting the program flow ? Like a multithreaded thing?

Thanks in advance.


Solution

  • without threading

    import time
    
    while True:
       time.sleep(1)
       do_stuff()
    

    with threading

    import threading 
    import time
    
    def my_func():
      while True:
        time.sleep(1)
        do_stuff()
    
    t1 = threading.Thread(target=my_func)  
    
    t1.start()