0

I want to run a function every x sec and never end unless interrupted. Using threading.Timer will spawn a new thread everytime. Is there a way to achieve the same in one thread?

Praniti Gupta
  • 149
  • 2
  • 3
  • 11

2 Answers2

4
import time

def job():
    ... code for the function you want to run

def execute():
    while(True):
        job()
        time.sleep(x) # where x is the interval between jobs in seconds
pragman
  • 1,564
  • 16
  • 19
0

There is a library called asyncio in Python 3.4+ which will allow you to do a repeated task every so often plus do your regular stuff. You put all your tasks on a loop that runs forever.

How can I periodically execute a function with asyncio? has an answer using this library.

Community
  • 1
  • 1
Back2Basics
  • 7,406
  • 2
  • 32
  • 45