use cache locks
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
from django.conf import settings
|
||||
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.core.cache import cache
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
from telebot import TeleBot
|
||||
@@ -16,20 +17,26 @@ class Feed(models.Model):
|
||||
check_interval = models.DurationField(help_text='in seconds')
|
||||
last_check = models.DateTimeField(null=True, blank=True)
|
||||
last_id = YAMLField(null=True, blank=True)
|
||||
lock = models.BooleanField(default=False)
|
||||
|
||||
config_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
|
||||
config_id = models.PositiveIntegerField()
|
||||
config = GenericForeignKey('config_type', 'config_id')
|
||||
|
||||
@property
|
||||
def lock_key(self):
|
||||
return 'feed-{}-lock'.format(self.pk)
|
||||
|
||||
@property
|
||||
def locked(self):
|
||||
return bool(cache.get(self.lock_key))
|
||||
|
||||
def run_check(self):
|
||||
if self.lock:
|
||||
if self.locked:
|
||||
return False
|
||||
if self.last_check and timezone.now() < self.last_check + self.check_interval:
|
||||
return False
|
||||
|
||||
self.lock = True
|
||||
self.save()
|
||||
cache.set(self.lock_key, 1, timeout=60)
|
||||
execute_feed.apply_async(args=(self.pk,), shadow=str(self))
|
||||
return True
|
||||
|
||||
|
Reference in New Issue
Block a user