Django中crontab的多个通知

f0ofjuux  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(128)

我在django/python中有一个crontab,代码如下。它同时发送多个通知,而不是发送单个通知。有什么问题吗?

`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()`
e37o9pze

e37o9pze1#

这是因为,Gunicorn工人同时称之为Cron作业。所以它才发了多条通知。作为一种解决方案,您可以使用缓存。

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

相关问题