Python - 如何创建一个等待给定时间执行函数的新线程
Python - How to create a new thread that waits for a given time to execute a function
我有一个特定 class 的对象列表,其中每个对象都有一个 unix 时间属性。我想执行一个函数
class Car:
def __init__(self, id, time):
self.id = id
self.time = time
objct = [Car(i, time_unix[i]) for i in range(10)]
其中 time_unix
是 unix 时间列表。我想创建一个新线程,它将 运行 'in parallel' 到检查当前时间的代码。如果当前时间等于对象的 unix_time
之一,将调用一个名为 drive
的新函数。
因此,我希望有一个线程始终保持警惕以调用 drive
函数,因为我可能有其他车辆在各自的时间开车。
你不需要时不时地查看当前时间。您可以计算线程需要等待多少秒并调用 time.sleep
.
结合this answer,你得到:
from multiprocessing.dummy import Pool as ThreadPool
from time import sleep
pool = ThreadPool(4)
cars = [('Car1', 3), ('Car2', 1), ('Car3', 2)]
def start_car(car, time_to_wait):
sleep(time_to_wait)
print("Starting %s after %d seconds" % (car, time_to_wait))
pool.starmap(start_car, cars)
它输出:
Starting Car2 after 1 seconds
Starting Car3 after 2 seconds
Starting Car1 after 3 seconds
您可以使用 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. docs
from 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()
示例输出:
2018-11-05 13:01:50.999886 tid:<Timer(Thread-2, started 139979005781760)> car_0: brumbrum
2018-11-05 13:01:52.000360 tid:<Timer(Thread-3, started 139978997389056)> car_1: brumbrum
2018-11-05 13:01:53.000452 tid:<Timer(Thread-4, started 139979005781760)> car_2: brumbrum
2018-11-05 13:01:54.000533 tid:<Timer(Thread-5, started 139978986825472)> car_3: brumbrum
2018-11-05 13:01:55.000625 tid:<Timer(Thread-6, started 139978978432768)> car_4: brumbrum
Process finished with exit code 0
我有一个特定 class 的对象列表,其中每个对象都有一个 unix 时间属性。我想执行一个函数
class Car:
def __init__(self, id, time):
self.id = id
self.time = time
objct = [Car(i, time_unix[i]) for i in range(10)]
其中 time_unix
是 unix 时间列表。我想创建一个新线程,它将 运行 'in parallel' 到检查当前时间的代码。如果当前时间等于对象的 unix_time
之一,将调用一个名为 drive
的新函数。
因此,我希望有一个线程始终保持警惕以调用 drive
函数,因为我可能有其他车辆在各自的时间开车。
你不需要时不时地查看当前时间。您可以计算线程需要等待多少秒并调用 time.sleep
.
结合this answer,你得到:
from multiprocessing.dummy import Pool as ThreadPool
from time import sleep
pool = ThreadPool(4)
cars = [('Car1', 3), ('Car2', 1), ('Car3', 2)]
def start_car(car, time_to_wait):
sleep(time_to_wait)
print("Starting %s after %d seconds" % (car, time_to_wait))
pool.starmap(start_car, cars)
它输出:
Starting Car2 after 1 seconds
Starting Car3 after 2 seconds
Starting Car1 after 3 seconds
您可以使用 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. docs
from 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()
示例输出:
2018-11-05 13:01:50.999886 tid:<Timer(Thread-2, started 139979005781760)> car_0: brumbrum
2018-11-05 13:01:52.000360 tid:<Timer(Thread-3, started 139978997389056)> car_1: brumbrum
2018-11-05 13:01:53.000452 tid:<Timer(Thread-4, started 139979005781760)> car_2: brumbrum
2018-11-05 13:01:54.000533 tid:<Timer(Thread-5, started 139978986825472)> car_3: brumbrum
2018-11-05 13:01:55.000625 tid:<Timer(Thread-6, started 139978978432768)> car_4: brumbrum
Process finished with exit code 0