[英]How to schedule a function in Flask App daily at every 5 minutes in Python
I would like to know how the check
function can be executed everyday at 5 minutes interval.我想知道如何每天每隔 5 分钟执行一次check
function。
import time
from flask import Flask
def check():
print(time.time())
app = Flask(__name__)
if __name__ == '__main__':
app.run()
Update更新
I tried the below but nothing happended.我尝试了以下但没有发生任何事情。
from apscheduler.triggers.combining import AndTrigger
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
trigger = AndTrigger([IntervalTrigger(minutes=5),
CronTrigger(day_of_week='mon,tue,wed,thu,fri)])
scheduler.add_job(job_function, trigger)
you need to schedule a Cron
job with Crontab
if you are planing to deploy your Flask
app on unix-like
server.如果您计划在unix-like
服务器上部署Flask
应用程序,则需要使用Crontab
安排Cron
作业。 for windows
server i have no clue how to do that but for sure you can plan tasks.对于windows
服务器,我不知道该怎么做,但可以肯定的是,您可以计划任务。
try python-crontab
package if you need to manipulate dynamically your crontab
, it's not mandatory for your case if you have the needed permissions on hosting server to insert an entry in user crontab file
如果您需要动态操作crontab
,请尝试python-crontab
user crontab file
package
few resources that may help you affording this很少有资源可以帮助您负担得起
python-crontab
) https://stackabuse.com/scheduling-jobs-with-python-crontab/ (关于python-crontab
的教程) you need a separate and standalone python script apart from your Flask
app since cron
can't execute a remote http request like curl / wget only shell/python/.. scripts, commands.., meaning in your case you can't insert https://myflaskapp.dev/check
in crontab like you need a separate and standalone python script apart from your Flask
app since cron
can't execute a remote http request like curl / wget only shell/python/.. scripts, commands.., meaning in your case you can't insert https://myflaskapp.dev/check
crontab 之类的
5 * * * * https://myflaskapp.dev/check
but the work around is that your cron
job execute standalone python script which send/execute an http request to that endpoint like:但解决方法是您的cron
作业执行独立的 python 脚本,该脚本向该端点发送/执行 http 请求,例如:
5 * * * * /home/webapps/www/myflaskapp.dev/check.py
in check.py
you can put simple python script using requests
library that just make an http request (get,post..) depending on your logic in check
function在check.py
中,您可以使用仅发出 http 请求(获取,发布..)的requests
库放置简单的 python 脚本,具体取决于您check
中的逻辑 function
# importing the requests library
import requests
# endpoint
URL = "http://myflaskapp.dev/check"
# defining a params dict for the parameters to be sent to the API (Optionnal)
PARAMS = {'param1': param1}
# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)
[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.