Timer 就是一个定时器,比如说在10s执行 t()
[code]
# -*- coding: utf-8 -*-
__author__ = 'songhao'
from threading import Timer, Thread
def t():
print("t")
for x in range(10):
tr = Timer(10, t)
tr.start()
Timer 源码:
class Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class
Timer
(
Thread
)
:
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=None, kwargs=None)
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def
__init__
(
self
,
interval
,
function
,
args
=
None
,
kwargs
=
None
)
:
Thread
.
__init__
(
self
)
self
.
interval
=
interval
self
.
function
=
function
self
.
args
=
args
if
args
is
not
None
else
[
]
self
.
kwargs
=
kwargs
if
kwargs
is
not
None
else
{
}
self
.
finished
=
Event
(
)
def
cancel
(
self
)
:
"""Stop the timer if it hasn't finished yet."""
self
.
finished
.
set
(
)
def
run
(
self
)
:
self
.
finished
.
wait
(
self
.
interval
)
if
not
self
.
finished
.
is_set
(
)
:
self
.
function
(
*
self
.
args
,
*
*
self
.
kwargs
)
self
.
finished
.
set
(
)
|
1314

被折叠的 条评论
为什么被折叠?



