python - 如果执行在超时内完成则从函数返回,否则进行回调

标签 python python-3.x asynchronous async-await python-asyncio

我有一个 Python 3.5 项目,没有使用任何异步功能。我必须实现以下逻辑:

def should_return_in_3_sec(some_serious_job, arguments, finished_callback):
    # Start some_serious_job(*arguments) in a task
    # if it finishes within 3 sec:
    #    return result immediately
    # otherwise return None, but do not terminate task.
    # If the task finishes in 1 minute:
    #    call finished_callback(result)
    # else:
    #    call finished_callback(None)
    pass

should_return_in_3_sec() 函数应该保持同步,但是我要编写任何新的异步代码(包括 some_serious_job())。

最优雅、最符合 Python 风格的方法是什么?

最佳答案

fork 一个正在做重要工作的线程,让它把结果写入队列,然后终止。从该队列中读取主线程,超时时间为三秒。如果发生超时,则启动另一个线程并返回 None。让第二个线程从队列中读取,超时时间为一分钟;如果也超时,请调用 finished_callback(None);否则调用 finished_callback(result)。

我画的是这样的:

import threading, queue

def should_return_in_3_sec(some_serious_job, arguments, finished_callback):
  result_queue = queue.Queue(1)

  def do_serious_job_and_deliver_result():
    result = some_serious_job(arguments)
    result_queue.put(result)

  threading.Thread(target=do_serious_job_and_deliver_result).start()

  try:
    result = result_queue.get(timeout=3)
  except queue.Empty:  # timeout?

    def expect_and_handle_late_result():
      try:
        result = result_queue.get(timeout=60)
      except queue.Empty:
        finished_callback(None)
      else:
        finished_callback(result)

    threading.Thread(target=expect_and_handle_late_result).start()
    return None
  else:
    return result

关于python - 如果执行在超时内完成则从函数返回,否则进行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42581175/

相关文章:

python - 如何在我的 Discord 服务器中获取消息作者的时区? (不和谐.py)

Python 在 Windows 上发送 SIGINT 信号子进程

jquery 当/然后(也当/完成)不等待

c# - 使用异步绑定(bind)时如何避免闪烁

Python:如何创建对引用的引用?

python - 为什么 Python 在语言环境模块中将德语和西类牙语(以及其他?)时间格式字符串存储为 %T?

python - 当键存储在另一个对象中时,如何访问字典值?

python - DecoderRNN 的输出包含额外维度 (Pytorch)

python - 如何使用 pd.concat 在 For 循环中将多个 DataFrame 合并在一起

python - `eventlet.spawn` 没有按预期工作