get_or_create and update_or_create save values more then once when executes at same time

276 Views Asked by At

get_or_create and update_or_create save values more then once when executes at same time

I am using djagno2.2 and python3.5

My code is something like this

class MyClass():

  def func1(arg = None):
    .......very large block of code.........
    This code can take 2-5 minutes to executes.
    .........
    MyModel.objects.get_or_create(name="abcd",defaults={Some params})   
    MyModel1.objects.update_or_create(name="abcd",defaults={Some params})

I used django-celery for background async processes and here is my tasks.py file

    from __future__ import absolute_import, unicode_literals

    from celery.decorators import periodic_task
    from celery.schedules import crontab


    @periodic_task(run_every=crontab(minute=00, hour=00))
    def every_day_midnight():
        """Executes every day at 00:00 am."""

        MyClass().func1()


    @periodic_task(run_every=crontab(minute='*/2'))
    def every_two_minutes():
        """Executes every 2 minutes"""

        MyClass().func1(arg)

Here i called MyClass().func1() daily midnight and same function executes with argument(arg) in every two minutes.

Now my problem is, This both functions are executes same time at midnight, so sometimes MyModel and myModel1 saves duplicate values. while i have used get_or_create and update_or_create

   MyModel.objects.get_or_create(name="abcd",defaults={Some params})   

   MyModel1.objects.update_or_create(name="abcd",defaults={Some params})

This problems occures due to both celery processes (every_day_midnight(),every_two_minutes()) executes at same time.

I have tried with transaction.automic but it didn't help me.

I want, When a process executes MyClass() or MyClass().func1 other process should be wait to complete that process. Other ideas/solutions also welcome

How can i do this. Thanks in advance

0

There are 0 best solutions below