How to perform periodic task with Flask in Python

前端 未结 3 1231
春和景丽
春和景丽 2020-12-14 08:28

I\'ve been using Flask to provide a simple web API for my k8055 USB interface board; fairly standard getters and putters, and Flask really made my life a lot easier.

<
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 08:38

    You could use cron for simple tasks.

    Create a flask view for your task.

    # a separate view for periodic task
    @app.route('/task')
    def task():
        board.read()
        board.digital_outputs = board.digital_inputs
    

    Then using cron, download from that url periodically

    # cron task to run each minute
    0-59 * * * * run_task.sh
    

    Where run_task.sh contents are

    wget http://localhost/task
    

    Cron is unable to run more frequently than once a minute. If you need higher frequency, (say, each 5 seconds = 12 times per minute), you must do it in tun_task.sh in the following way

    # loop 12 times with a delay
    for i in 1 2 3 4 5 6 7 8 9 10 11 12
    do
        # download url in background for not to affect delay interval much
        wget -b http://localhost/task
        sleep 5s
    done
    

提交回复
热议问题