Python Apscheduler不会停止函数执行

如何解决Python Apscheduler不会停止函数执行

我正在尝试执行面部检测功能,并使用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.'

我的While True函数中有一个detection条件,所有检测逻辑都在其中运行。即使我确定了停止时间,也可能是它永远不会停止的原因吗?我该如何解决这个问题?

编辑。从我的detection函数中-loop时(删除了不必要的部分):

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循环的beginnig中检查环境变量:

while True:
        if os.environ.get('run') == 'stop':
            stream.stream.release()
            exit()

我想要的是将调度功能集成到此。我不想做单独的功能,因为我希望能够手动停止以计划开始的检测。我有什么技巧可以实现这一目标?

编辑3。日程安排现在正在工作。手动启动也起作用,而停止则意味着停止检测面部。尽管以schedule开始的功能仍然继续,它根本没有迭代到检测部分,因为有一个os.environ['run'] = 'stop' -flag。知道如何停止函数执行吗? 这是我进行的while -loop检查:

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函数转换为类,并在初始化时通过c 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.'



这应该可以解决问题

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res