您可以使用threading.Timer在指定的时间间隔后在单独的线程中调度目标函数的执行。在Timer Objects
This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.
Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method. The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user. docsfrom threading import Timer, current_thread
from datetime import datetime
def drive(car):
print(f'{datetime.now()} tid:{current_thread()} {car}: brumbrum')
class Car:
def __init__(self, id, time):
self.id = id
self.time = time
if __name__ == '__main__':
N_CARS = 5
time_unix = {k: v for k, v in zip(range(N_CARS), range(N_CARS))}
cars = [Car(f'car_{i}', time_unix[i]) for i in range(N_CARS)]
for car in cars:
interval = car.time # calculate delay in seconds for execution here
t = Timer(interval=interval, function=drive, args=(car.id,))
t.start()
输出示例:
^{pr2}$