Run Certain Code Every N Seconds

Run certain code every n seconds

import threading

def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

What is the best way to repeatedly execute a function every x seconds?

If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

Run certain code after x seconds, every n seconds in python

import threading
import time

def printit():
threading.Timer(n, printit).start()
print "Hello, World!"

threading.Timer(x, printit)

How to print every x seconds while rest of code runs without being stopped?

One way is to use time.time to measure how much time has passed (will print 'hi' every 5 seconds or so, this is less precise because if some part of the loop takes more time, it may print later than expected):

import time

start = time.time()
while True:
# run some code

current_time = time.time()
if current_time - start >= 5:
print('hi')
start = current_time

Or use threading module to run a loop concurrently (will print 'hi' every 5 seconds, this is also more precise, because the time measurement is not affected by the speed of the "main" loop (as is the case with the above code)):

import time
import threading

def loop():
while True:
time.sleep(5)
print('hi')

threading.Thread(target=loop).start()

while True:
# run some code
pass # this can be removed after you add the actual code

Run a python function every second

This will do it, and its accuracy won't drift with time.

import time

start_time = time.time()
interval = 1
for i in range(20):
time.sleep(start_time + i*interval - time.time())
f()

Call function every x seconds (Python)

Just remember when the next iteration is supposed to happen, roughly like this (not fully working code, I'm sure you can figure it out from here):

import time
nexttime = time.time()
while True:
func() # take t sec
nexttime += 10
sleeptime = nexttime - time.time()
if sleeptime > 0:
time.sleep(sleeptime)

Run certain code every x seconds

How about

import time
while True:
time.sleep(1)
print ('Hello world')

Run a function every n seconds in python with asyncio

asyncio does not ship with a builtin scheduler, but it is easy enough to build your own. Simply combine a while loop with asyncio.sleep to run code every few seconds.

async def every(__seconds: float, func, *args, **kwargs):
while True:
func(*args, **kwargs)
await asyncio.sleep(__seconds)

a = asyncio.get_event_loop()
a.create_task(every(1, print, "Hello World"))
...
a.run_forever()

Note that the design has to be slightly different if func is itself a coroutine or a long-running subroutine. In the former case use await func(...) and in the latter case use asyncio's thread capabilities.



Related Topics



Leave a reply



Submit