多个来自Django中的crontab的通知

huangapple go评论69阅读模式
英文:

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 a 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 = "<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()

(Note: I have removed the HTML encoding for clarity.)

英文:

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 = &quot;some text&quot;
                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&quot;&lt;b&gt;*******HISOBOT*******&lt;/b&gt;\n&quot; \
            send_message_telegram(text, SEND_STATISTIC_GROUP_ID)
            time.sleep(100)
    except:
        send_message_telegram
def start():
    scheduler = BackgroundScheduler({&#39;apscheduler.timezone&#39;: &#39;Asia/Tashkent&#39;})

    scheduler.add_job(send_statistics, &#39;cron&#39;, hour=9)
    scheduler.start()`

答案1

得分: 1

因为Gunicorn的工作进程同时调用这个定时任务,所以会发送多次通知。作为解决方案,你可以使用缓存。

from django.core.cache import cache

def send_statistics():
    # 尝试获取锁
    if cache.add('statistics_lock', 'true', timeout=600):
        try:
            # 在这里执行剩余的函数...
            ...
        finally:
            # 完成后始终确保释放锁定
            cache.delete('statistics_lock')
    else:
        # 如果无法获取锁定,说明另一个实例已经在运行任务
        pass
英文:

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(&#39;statistics_lock&#39;, &#39;true&#39;, timeout=600):
        try:
            # The rest of your function here...
            ...
        finally:
            # Always make sure to release the lock when done
            cache.delete(&#39;statistics_lock&#39;)
    else:
        # If we couldn&#39;t acquire the lock, that means another instance is already running the task
        pass```


</details>



huangapple
  • 本文由 发表于 2023年6月15日 12:10:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定