Search code examples
pythondjangocron

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

  • 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```