setTimeout
https://docs.python.org/3.6/library/sched.html
The
sched
module defines a class which implements a general purpose event scheduler:
- class
sched.
scheduler
(timefunc=time.monotonic, delayfunc=time.sleep)The
scheduler
class defines a generic interface to scheduling events. It needs two functions to actually deal with the “outside world” — timefunc should be callable without arguments, and return a number (the “time”, in any units whatsoever). If time.monotonic is not available, the timefunc default is time.time instead. The delayfunc function should be callable with one argument, compatible with the output of timefunc, and should delay that many time units. delayfunc will also be called with the argument0
after each event is run to allow other threads an opportunity to run in multi-threaded applications.
>>> import sched, time >>> s = sched.scheduler(time.time, time.sleep) >>> def print_time(a='default'): ... print("From print_time", time.time(), a) ... >>> def print_some_times(): ... print(time.time()) ... s.enter(10, 1, print_time) ... s.enter(5, 2, print_time, argument=('positional',)) ... s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) ... s.run() ... print(time.time()) ... >>> print_some_times() 930343690.257 From print_time 930343695.274 positional From print_time 930343695.275 keyword From print_time 930343700.273 default 930343700.276
setInterval
https://github.com/Hzzkygcs/setInterval-python
Sometimes, when you're writing code in python, you have to make a function that needs to be executed every certain amount of time. This class will help you do that easily and dynamically on python. Open all of the flexibility to maintain the interval.
To declare an interval function, you just need to call the setInterval class. The parameter is as follows:
setInterval(Function, Interval, Arguments=[])
TheInterval
is in second, by using number data type. TheArguments
is the arguments you need to pass to the function in an array.Here's a simple example:
def interval(name="world"): print(f"Hello {name}!") # function named interval will be called every two seconds # output: "Hello world!" interval1 = setInterval(interval, 2) # function named interval will be called every 1.5 seconds # output: "Hello Jane!" interval2 = setInterval(interval, 1.5, ["Jane"])
实现代码:
https://github.com/Hzzkygcs/setInterval-python/blob/master/set_interval.py
从中可以看出其使用原生API threading.Timer 实现。原型如:
https://stackoverflow.com/questions/33473899/how-set-a-loop-that-repeats-at-a-certain-interval-in-python
from threading import Timer, Thread def call_at_interval(time, callback, args): while True: timer = Timer(time, callback, args=args) timer.start() timer.join() def setInterval(time, callback, *args): Thread(target=call_at_interval, args=(time, callback, args)).start()