Skip to content

Instantly share code, notes, and snippets.

@stamat
Created April 12, 2013 10:50
Show Gist options
  • Save stamat/5371218 to your computer and use it in GitHub Desktop.
Save stamat/5371218 to your computer and use it in GitHub Desktop.
Python setInterval() equivalent
import threading
def set_interval(func, sec):
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
@EECSGEEK
Copy link

EECSGEEK commented Dec 1, 2017

How to stop the timer?

@micalevisk
Copy link

to stop the timer, you may use cancel method, like t.cancel()
https://stackoverflow.com/questions/9812344/cancellable-threading-timer-in-python

@4sushi
Copy link

4sushi commented Nov 20, 2019

An other option: Event scheduler. https://docs.python.org/3/library/sched.html

@Animenosekai
Copy link

I get an error while doing this;

Exception in thread Thread-13:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 1254, in run
    self.function(*self.args, **self.kwargs)
  File "myprogram.py", line 56, in func_wrapper
    func()
TypeError: 'NoneType' object is not callable

@natsworkspace
Copy link

I get an error while doing this;

Exception in thread Thread-13:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 1254, in run
    self.function(*self.args, **self.kwargs)
  File "myprogram.py", line 56, in func_wrapper
    func()
TypeError: 'NoneType' object is not callable

the thing i think ur doing is, doing something like this:
image

do this instead:
image

@ashkangoleh
Copy link

is there other way to use it on async functions?

@anchikhorov
Copy link

this not will work as expected, it python no such analog

@craigbarrington
Copy link

craigbarrington commented Aug 8, 2024

Just make a function in an infinite loop:

def one_second_interval():
.....print("x")
.....time.sleep(1)

while True:
.....one_second_interval()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment