python创建线程函数,Python如何创建一个等待给定时间执行函数的新线程

您可以使用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}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值