https://www.cnblogs.com/ywhyme/p/10660411.html 的升级版

可以知道当前是卡在哪一个 task 甚至是多少行

import asyncio
import os
import queue
import signal
import time
import threading
import logging # logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(filename)s : %(levelname)s %(message)s", )
logging.basicConfig(level=logging.DEBUG) # 魔改部分
# 魔改原因, 在 loop.debug 为 True 的时候才会给 loop 设置 _current_handle
from asyncio import events class Handle(events.Handle):
def _run(self):
self._loop._current_handle = self
super()._run() events.Handle = Handle
# 魔改结束 async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}") async def test():
for i in range(100):
print("sleep--", i)
time.sleep(1) def handler(signum, frame):
print('Signal handler called with signal', signum)
raise Exception("Kill the task") signal.signal(signal.SIGTERM, handler) async def main():
await asyncio.gather(
test(),
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
return_exceptions=True
) def check(co_name, threshold: int = 60) -> bool:
"""连续的记录超过阈值"""
i = 0
for item in q:
if item == co_name:
i += 1
else:
break
if i >= threshold:
return True
else:
return False def asyncio_monitor(loop, step: int = 1):
while not stop:
if hasattr(loop._current_handle, "_callback"):
callback = loop._current_handle._callback
task = getattr(callback, "__self__") # Task co_name = task._coro.cr_code.co_name # task._coro.cr_code.co_name # coro name if check(co_name, 10):
# 长时间堵塞, 抛出异常让 task 结束
if pid != None:
os.system(f"kill -{signal.SIGTERM} {pid}") if task._state == "PENDING":
q.appendleft(co_name) # info 为一个的回显字符串 info = str(getattr(callback, "__self__", callback))
print(info)
#
# coro = task._coro.co_name # coro name
# task._state # futures/_base.py:25
# time.sleep(step) def run_asyncio(loop):
global stop
# loop.set_debug(True)
loop.run_until_complete(main())
stop = True if __name__ == '__main__':
pid = os.getpid()
print(pid)
stop = False q = queue.deque(maxlen=100) loop = asyncio.get_event_loop() t1 = threading.Thread(target=asyncio_monitor, args=(loop,))
t1.start() run_asyncio(loop)

asyncio 自动跳出长时间堵塞的 task的更多相关文章

  1. 在asyncio 中跳出正在执行的task

    需求描述 代码在asyncio的框架中运行, 但是一旦一个task出现了长时间的堵塞,我们要跳过这个task(代码可能是用户输入的,例如用户编写的插件) 代码如下 (其中大部分代码出自官方的 asyn ...

  2. WPF窗口长时间无人操作鼠标自动隐藏

    在软件开发中有时会有等待一段时间无人操作后隐藏鼠标,可能原因大致如下: 1.为了安全性,特别是那些需要用到用户名和密码登录服务端的程序,常常考虑长期无人操作,程序自动跳转到用户登录界面: 2.软件为了 ...

  3. JavaScript长时间未操作自动退出登录

    主要是通过mouseover 来监听有没有进行当前页面操作,通过未操作时间和设定退出的时间做比较,从而退出登录. var oldTime = new Date().getTime(); var new ...

  4. web页面长时间未操作自动退出登录

    var lastTime = new Date().getTime(); var currentTime = new Date().getTime(); * * ; //设置超时时间: 10分 $(f ...

  5. jdbc 数据库连接 长时间空闲 断开连接 ApplicationContext.xml

    数据库连接 长时间空闲 断开连接solution: <property name="validationQuery" value="select 1"/& ...

  6. wireshark长时间抓包分多个文件

    前言 说一说这个问题的由来,一般使用wireshark不需要长时间抓包的,但是有时候遇到网络通信中非常棘手的问题,例如一个小时出现一次或者几个小时出现一次问题的情况,这种情况下就必须长时间抓包了.但是 ...

  7. ios之申请后台延时执行和做一个假后台的方法(系统进入长时间后台后,再进入前台部分功能不能实现)

    转自:http://sis hu ok.com/forum/blogCategory/showByCategory.html?categories_id=138&user_id=10385   ...

  8. 实现iOS长时间后台的两种方法:Audiosession和VOIP(转)

    分类: Iphone2013-01-24 14:03 986人阅读 评论(0) 收藏 举报 我们知道iOS开启后台任务后可以获得最多600秒的执行时间,而一些需要在后台下载或者与服务器保持连接的App ...

  9. WinForm触摸屏程序功能界面长时间不操作自动关闭回到主界面 z

    操作者经常会在执行了某操作后,没有返还主界面就结束了操作然后离开了,程序应该关闭功能窗体自动回到主界面方便下一位操作者操作.那么对于WinForm程序怎么实现呢? 实现原理:拦截Application ...

随机推荐

  1. javascript--闭包与this

    理解javascript中的闭包与this http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html http: ...

  2. Java内联函数

    1.内联函数就是指函数在被调用的地方直接展开,编译器在调用时不用像一般函数那样,參数压栈,返回时參数出栈以及资源释放等,这样提高了程序运行速度. 2.Java语言中有一个keywordfinal来指明 ...

  3. BEGINNING SHAREPOINT&#174; 2013 DEVELOPMENT 第12章节--SP 2013中远程Event Receivers 总结

    BEGINNING SHAREPOINT® 2013 DEVELOPMENT 第12章节--SP 2013中远程Event Receivers  总结         本章节向你介绍了SP平台上eve ...

  4. ZOJ 1654--Place the Robots【二分匹配 &amp;&amp; 经典建图】

    Place the Robots Time Limit: 5 Seconds      Memory Limit: 32768 KB Robert is a famous engineer. One ...

  5. 神经网络中的激活函数——加入一些非线性的激活函数,整个网络中就引入了非线性部分,sigmoid 和 tanh作为激活函数的话,一定要注意一定要对 input 进行归一话,但是 ReLU 并不需要输入归一化

    1 什么是激活函数? 激活函数,并不是去激活什么,而是指如何把“激活的神经元的特征”通过函数把特征保留并映射出来(保留特征,去除一些数据中是的冗余),这是神经网络能解决非线性问题关键. 目前知道的激活 ...

  6. nyoj--491--幸运三角形(dfs)

    幸运三角形 时间限制:1000 ms  |  内存限制:65535 KB 难度:3 描述 话说有这么一个图形,只有两种符号组成('+'或者'-'),图形的最上层有n个符号,往下个数依次减一,形成倒置的 ...

  7. JDK8新特性:函数式接口

    一,定义 函数式接口,英文为Functional Interface.首先它是一个接口,那么它与其它接口有什么不同呢?不同点就是在这个接口中只允许有一个抽象方法. 这里的只允许一个抽象方法不包括以下几 ...

  8. strlen和mb_strlen

    在PHP中,strlen与mb_strlen是求字符串长度的函数,但是对于一些初学者来说,如果不看手册,也许不太清楚其中的区别.下面通过例子,讲解这两者之间的区别. 先看例子: <?php // ...

  9. 读入图片显示scipy.misc module has no attribute imread?

    >>> import scipy >>> scipy.misc <module 'scipy.misc' from 'C:\Python27\lib\site ...

  10. Irrlicht 1.8.4 + Win7 + VC2015 + x64 +OpenGL编译

    1. 下载irrlicht1.8.4 https://nchc.dl.sourceforge.net/project/irrlicht/Irrlicht%20SDK/1.8/1.8.4/irrlich ...