sched
It can be used for timed tasks. The only thing to note is that these tasks run in one thread. If the previous tasks take too long, the later tasks will be delayed.
But its use method is still very simple, mainly encapsulates a classscheduler
import sched
import time
def printName(name):
print(name,"@",time.time())
s = sched.scheduler()
s.enter(5,1,printName,("5 - 1",))
s.enter(5,2,printName,("5 - 2",))
s.enter(10,1,printName,("10 - 1",))
s.run()
Among them, enter
is s
the event added in, the first two parameters of which represent the delay time and task execution sequence respectively; printName
is the function to be executed, ("5-1",)
is the parameter list, indicating the first task to be executed in the 5s.
Its execution result is as follows
5 - 1 @ 1649725436.606954
5 - 2 @ 1649725436.6229577
10 - 1 @ 1649725441.6388779
If a delay is added to the function, subsequent tasks will be delayed
def printName(name):
print(name,"@",time.time())
time.sleep(6)
Its output is
5 - 1 @ 1649725617.7624931
5 - 2 @ 1649725623.7689147
10 - 1 @ 1649725629.7827168
In contrast enter
to cancel(evt)
sum empty
, the former can delete an event, and the latter can clear all events.
If thread
used together, the sched
blocking problem can be solved.
import sched
import threading
import time
def printNameByThread(name):
threading.Thread(target=printName,args=[name]).start()
s = sched.scheduler()
s.enter(5,1,printNameByThread,("5 - 1",))
s.enter(5,2,printNameByThread,("5 - 2",))
s.enter(10,1,printNameByThread,("10 - 1",))
s.run()
Its output is
5 - 1 @ 1649725777.2276525
5 - 2 @ 1649725777.2276525
10 - 1 @ 1649725782.2158542
Therefore, skilled use thread
of and sched
, you can arrange timed tasks.