Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

multiple notifications from crontab in Django

I have a crontab in django/python, the code is given below. It is sending multiple notifications at the same time instead of sending single one. what is the problem?

`def send_statistics():
    today = date.today()
    yesterday = today - timedelta(days=1)
    try:
        if StatisticModel.objects.filter(date=yesterday).exists():
            stat = StatisticModel.objects.get(date=yesterday)
            if not stat.is_send:
                text = "some text"
                send_message_telegram(text, SEND_STATISTIC_GROUP_ID)
                stat.is_send = True
                stat.save()
                time.sleep(100)
        else:
            StatisticModel.objects.create(is_send=True, date=yesterday)
            text = f"<b>*******HISOBOT*******</b>\n" \
            send_message_telegram(text, SEND_STATISTIC_GROUP_ID)
            time.sleep(100)
    except:
        send_message_telegram
def start():
    scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Tashkent'})

    scheduler.add_job(send_statistics, 'cron', hour=9)
    scheduler.start()`

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

it’s because, gunicorn workers are calling this cron job simultaneously. That’s why it’s sending multiple notifications.
As a solution, you may use caching.

from django.core.cache import cache

def send_statistics():
    # Try to acquire the lock
    if cache.add('statistics_lock', 'true', timeout=600):
        try:
            # The rest of your function here...
            ...
        finally:
            # Always make sure to release the lock when done
            cache.delete('statistics_lock')
    else:
        # If we couldn't acquire the lock, that means another instance is already running the task
        pass```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading