How to Schedule a Function to Run Every Hour on Flask

How to schedule a function to run every hour on Flask?

You can use BackgroundScheduler() from APScheduler package (v3.5.3):

import time
import atexit

from apscheduler.schedulers.background import BackgroundScheduler

def print_date_time():
print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))

scheduler = BackgroundScheduler()
scheduler.add_job(func=print_date_time, trigger="interval", seconds=60)
scheduler.start()

# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())

Note that two of these schedulers will be launched when Flask is in debug mode. For more information, check out this question.

Schedule a function at particular time of day using a flask app

Simple thread if server startted standalone:

if __name__== '__main__':
import threading

threading.Thread(target=programare).start()
app.run(debug=True)

If server deployed with wsgi or etc I suggest to run shedule separately.

Scheduling Python Script to run every hour accurately

Maybe this can help: Advanced Python Scheduler

Here's a small piece of code from their documentation:

from apscheduler.schedulers.blocking import BlockingScheduler

def some_job():
print "Decorated job"

scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()

How to run Python script to run daily using apscheduler with flask?

you could try this

job = scheduler.add_job(test_job, 'cron', day_of_week ='mon-sun', hour=16, minute=00)

How to perform periodic task with Flask in Python

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

How to schedule a python function to run every hour at specific minute (ex 00, 10, 20) with apscheduler

You can try using the cron trigger.

sched.add_job(
demo_job,
trigger='cron',
minute='*/10',
hour='*'
)

The expression */10 will fire the job at every tenth minute, starting from the minimum value. Crontab ref



Related Topics



Leave a reply



Submit