英文:
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 = "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()`
答案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('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```
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论