Search code examples
python-3.xcelery

Celery periodic task with select DB data



I set up sending birthday greetings based on the data in the database.
Using Python and Celery(on_after_configure).
It looks like this:
from flask import Flask
from celery.schedules import crontab
from celery import Celery
from datetime import datetime

app = Flask(__name__)

today = datetime.now().strftime("%d/%m")
    
    @celery.on_after_configure.connect
    def setup_periodic_tasks(sender, **kwargs):
        emails = DB.get_email_today(today) #getting a list of birthday emails today
        for row in emails:
            email = row['email']
            first_name = row['first_name']
            last_name = row['last_name']
            sender.add_periodic_task(
                crontab(hour=12, minute=20),
                sender.send_email.s(email, first_name, last_name),
            )

The problem is that today is calculated only at the moment the application starts and is not updated every day.
Tell me how this can be configured?


Solution

  • You are defining the today variable in the global scope of the application, therefore it is set when you first run the application. You could add a task, which includes getting the current date and the rest of the logic execution and then schedule it with @app.on_after_configure.connect

    @app.task
    def task():
        current_datetime = datetime.now()
        emails = DB.get_email_today()
        ...
        *Your desired code logic*
    
    @app.on_after_configure.connect
    def schedule_task(sender, **kwargs):
        sender.add_periodic_task(crontab(hour=12, minute=20), task.s(), "Send 
        Birthday Mails")
        ....
    

    Reference here