[英]Python Apscheduler not stopping function execution
我正在尝试执行我的人脸检测功能并使用 Apscheduler 仅在特定时间之间运行该功能。 我可以正确启动该函数,但end_time
参数似乎根本不起作用,该函数一直在运行,直到手动关闭。
这是开始时间表的路线:
@app.route("/schedule/start", methods = ['POST'])
def create():
sched = BlockingScheduler()
sched.add_job(detection, 'cron', start_date='2020-10-01 15:33:00', end_date='2020-10-01 15:33:05')
sched.start()
return 'Schedule created.'
我的detection
功能中有一个While True
条件,所有detection
逻辑都在其中运行。 难道这就是即使我确定了停止时间它也永远不会停止的原因吗? 我该如何解决这个问题?
编辑。 While -loop 从我的detection
- 功能(删除了不必要的部分):
while True:
frame = stream.read()
frame = imutils.resize(frame, width=900)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame = np.dstack([frame, frame, frame])
# frame = cv2.flip(frame, 0)
faces = faceCascade.detectMultiScale(
frame,
scaleFactor=1.1,
minNeighbors=3,
# minSize=(10, 10),
# maxSize=(50, 50),
# flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
name = str(currentframe) + '.jpg'
print('Creating...' + name)
cv2.imwrite(os.path.join(parent_dir, name), frame)
currentframe += 1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
编辑2。 我按照下面的建议尝试并收到此错误: TypeError: func must be a callable or a textual reference to one
。
我还想集成手动启动和停止人脸检测功能的功能。 我可以这样做:
@app.route("/start", methods = ['POST'])
def start():
os.environ['run'] = 'running'
detection()
return 'Detection started'
@app.route("/stop", methods = ['POST'])
def stop():
os.environ['run'] = 'stop'
return 'Detection stopped.'
然后在我的detection.py
我只是在 while 循环的开头检查环境变量:
while True:
if os.environ.get('run') == 'stop':
stream.stream.release()
exit()
我想要的是将调度功能集成到此。 我不想创建单独的函数,因为我希望能够手动停止按计划启动的检测。 我如何实现这一目标的任何提示?
编辑3。 时间表现在正在运行。 手动启动也有效,停止也意味着停止检测人脸。 以 schedule 开头的函数仍然继续运行,它根本没有迭代到检测部分,因为有一个os.environ['run'] = 'stop'
-flag。 知道如何停止函数执行吗? 这是我的 while 循环检查:
while True:
if self.end_date <= datetime.now() or os.environ.get('run') == 'stop':
stream.stream.release()
exit()
手动启动时,停止功能按预期工作,但停止计划作业时,它会一直循环直到满足 end_date 时间。
您需要有一些条件来结束您的 while 循环,因为它现在是无限的,传递开始/结束时间并转换为日期时间并尝试匹配while end_date_time =< now:
然后退出任务。 如果您需要传递开始/结束日期,可以将您的detection
函数转换为类,并在初始化时传递end_date
当您希望 cron 作业停止时。
# detection.py
from datetime import datetime
class Detection:
def __init__(self, end_date):
self.end_date = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S.%f')
def detection(self):
print(self.end_date)
while self.end_date <= datetime.utcnow():
print('works')
# routes.py
# And then do it like this when starting cron
import Detection
def create():
start_date = '2020-10-02 01:48:00.192386'
end_date = '2020-10-02 05:50:00.192386'
dt = Detection(end_date)
sched = BlockingScheduler()
sched.add_job(dt.detection, 'cron', start_date=start_date, end_date=end_date)
sched.start()
return 'Schedule created.'
这应该可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.