Python uses a simple Timer class instance encapsulated by a thread
This example describes a simple Timer class encapsulated by a thread in python. Share it with you for your reference. The specific implementation method is as follows:
?
|
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
27
28
29
30
31
32 |
From threading import Timer
Class MyTimer:
Def _ init _ (self ):
Self. _ timer = None
Self. _ tm = None
Self. _ fn = None
Def _ do_func (self ):
If self. _ fn:
Self. _ fn ()
Self. _ do_start ()
Def _ do_start (self ):
Self. _ timer = Timer (self. _ tm, self. _ do_func)
Self. _ timer. start ()
Def start (self, tm, fn ):
Self. _ fn = fn
Self. _ tm = tm
Self. _ do_start ()
Def stop (self ):
Try:
Self. _ timer. cancel ()
Except t:
Pass
Def hello ():
From datetime import datetime
Print ("hello world! ", Datetime. now ())
If _ name _ = '_ main __':
Mt = MyTimer ()
Mt. start (2, hello)
For I in range (10 ):
Import time
Time. sleep (1)
Mt. stop ()
|
I hope this article will help you with Python programming.