我正在尝试运行一组代码,这些代码在UTC时间的5秒内完全启动,从偶数分钟开始。
例如,它将完全执行每个样本:
11:20:45
11:20:50
11:20:55
11:21:00
11:21:05
11:21:10
我希望无论代码块的执行时间如何都会发生这种情况,如果运行代码是即时的或3秒钟,我仍然希望以5秒的UTC时间间隔执行。
不完全确定怎么做,虽然我认为datetime.datetime.utcnow().timestamp() - (datetime.datetime.utcnow().timestamp() % 5.0) + 5
让我下一个即将到来的开始时间?
答案 0 :(得分:1)
您可以使用python的scheduler模块:
from datetime import datetime
import sched, time
s = sched.scheduler(time.time, time.sleep)
def execute_something(start_time):
print("starting at: %f" % time.time())
time.sleep(3) # simulate a task taking 3 seconds
print("Done at: %f" % time.time())
# Schedule next iteration
next_start_time = start_time + 5
s.enterabs(next_start_time, 1, execute_something, argument=(next_start_time,))
next_start_time = round(time.time() + 5, -1) # align to next to 10sec
s.enterabs(next_start_time, 1, execute_something, argument=(next_start_time,))
print("Starting scheduler at: %f" % time.time())
s.run()
# Starting scheduler at: 1522031714.523436
# starting at: 1522031720.005633
# Done at: 1522031723.008825
# starting at: 1522031725.002102
# Done at: 1522031728.005263
# starting at: 1522031730.002157
# Done at: 1522031733.005365
# starting at: 1522031735.002160
# Done at: 1522031738.005370
答案 1 :(得分:0)
使用time.sleep
等到所需的时间。请注意,这是近似值;特别是当系统处于高负载时,您的过程可能无法及时唤醒。你可以increase process priority增加你的机会。
为了避免阻塞等待线程,可以在单独的线程中运行任务,方法是为每个任务构建一个新线程或使用(更快)thread pool,如下所示:
import concurrent.futures
import time
def do_something(): # Replace this with your real code
# This code outputs the time and then simulates work between 0 and 10 seconds
import datetime
import random
print(datetime.datetime.utcnow())
time.sleep(10 * random.random())
pool = concurrent.futures.ThreadPoolExecutor()
while True:
now = time.time()
time.sleep(5 - now % 5)
pool.submit(do_something)