python中断言断语_Python中的实时中断

I have a Python 2.7 program running an infinite while loop and I want to incorporate a timer interrupt.

What I aim to do is to set off a timer at some point in the loop, and when 5 seconds have elapsed I want the code to branch to a specific part of the while loop.

What I have been doing so far is the following:

in each iteration of the while loop I am checking how much time has elapsed when I reach that point in the code using

time.clock()

and if the difference exceeds 5 I run the chunk of code I mean to run

However that way 7 seconds might pass before I evaluate the time, it will be >5sec but I want to go there exactly when 5 seconds pass

Also, I need this to work for more than 1 counter (possibly up to a 100) but I do not want the interrupts to interrupt each other. Using Timer did not work either.

I know this can be done using timer interrupts in assembly but how can I do that in python?

解决方案

If a single event is to be handled, then the easiest way is to use the signal framework which is a standard module of Python.

However, if we need a fully-fledged scheduler, then we have to resort to another module: sched. Here is a pointer to the official documentation. Please be aware, though, that in multi-threaded environments sched has limitations with respect to thread-safety.

Another option is the Advanced Python Scheduler, which is not part of the standard distribution.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值