DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

3 1

How to execute a recurrent task in a Flask app?

In some projects, we need to do dome recurrent tasks while running a Flask API.

So do be able to do it in a Flask project, we need to use APScheduler.
With this tool, we are able to create background schedulers which will execute our recurrent task.


Install

Using pip, you can install the library as follow.

pip install APScheduler


Usage

To use it, check the following example.

import time
import atexit

from apscheduler.schedulers.background import BackgroundScheduler

# Declaration of the task as a function.
def print_date_time():
    print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))


# Create the background scheduler
scheduler = BackgroundScheduler()
# Create the job
scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
# Start the scheduler
scheduler.start()

# /!\ IMPORTANT /!\ : Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
Enter fullscreen mode Exit fullscreen mode

Links


I hope it will help you! 🍺

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay