Skip to content

Commit

Permalink
Monkey-patch django cache redis to support locking
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomáš Daniel committed Oct 8, 2024
1 parent fef6f42 commit 2ffa8bf
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions django_celery_extensions/beat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.core.cache import caches
from django.core.cache.backends.redis import RedisCacheClient
from django.core.exceptions import ImproperlyConfigured

try:
Expand All @@ -8,17 +9,24 @@
except ImportError:
raise ImproperlyConfigured('Missing celery library, please install it')

try:
from redis_cache import RedisCache
except ImportError:
raise ImproperlyConfigured('Missing redis_cache library, please install it')
from redis.lock import Lock

from .config import settings


logger = get_logger(__name__)


def monkey_patch_django_redis():
def lock(self, key, timeout, sleep):
return Lock(self.get_client(), key, timeout, sleep)

RedisCacheClient.lock = lock


monkey_patch_django_redis()


class LockedPersistentScheduler(PersistentScheduler):

lock = None
Expand All @@ -44,14 +52,10 @@ def close(self):
@beat_init.connect
def acquire_distributed_beat_lock(sender=None, **kwargs):
scheduler = sender.scheduler

cache = caches[settings.CACHE_NAME]

if not isinstance(cache, RedisCache):
raise ImproperlyConfigured('Only redis cache is allowed to use LockedPersistentScheduler')

logger.debug('beat: Acquiring lock...')
lock = caches[settings.CACHE_NAME].lock(
lock = cache.lock(
scheduler.lock_key,
timeout=scheduler.lock_timeout,
sleep=scheduler.lock_sleep
Expand Down

0 comments on commit 2ffa8bf

Please sign in to comment.