简体   繁体   中英

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.

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. for windows server i have no clue how to do that but for sure you can plan tasks.

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

few resources that may help you affording this

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

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:

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

# 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) 

[...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM