我在脚本中使用模块APScheduler,我使用BlockingScheduler。我有一份定期工作。如果这个作业raise是Exception,无论我在try中使用它还是让它传播,我的线程都不会返回。然后我到达max_instance,不再执行作业。
使用Execptions时如何在线程中管理BlockingScheduler
这里我的MWE说明了我的问题:
from apscheduler.schedulers.blocking import BlockingScheduler
import threading
class x:
def __init__(self):
self._lock = threading.Lock()
def __enter__(self):
print("ENTER")
self._lock.acquire()
print("LOCK")
raise Exception("ERROR")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("EXIT")
self._lock.release()
print("UNLOCK")
a = x()
def test():
print("TEST")
with a:
print("WITH")
pollingScheduler = BlockingScheduler()
pollingScheduler.add_job(test, 'interval', seconds=1, max_instances=1)
pollingScheduler.start()我期望在引发异常时必须调用__exit__()方法,即使引发异常的是__enter__()。在睾丸之后,我发现没有调用__exit__()就是这样的情况。因此,它会导致死锁和线程阻塞。
我该怎么解决这个问题?看来__enter__()不能引发异常。是对的吗?
发布于 2016-01-14 16:51:52
这里的问题是,只有当__exit__成功完成时,才会调用__enter__。由于在__enter__中引发异常,锁处于已获取状态,因此在尝试获取锁时,作业的后续运行将挂起。如果希望在__enter__中出现异常,请将其包装在一个try...except块中,如果引发异常,该块将释放锁。
https://stackoverflow.com/questions/34773749
复制相似问题