如何使用计时器调用函数?
models.py
# Choices
time = [
('1', 'Morning'),
('2', 'Afternoon'),
('3', 'Evening'),
('4', 'Night'),
]
# Model
class Calendar(models.Model):
user = models.ForeignKey(AUTH_USER_MODEL,on_delete=models.SET_NULL)
date = models.DateField()
time = models.CharField(max_length=10, choices=time)
location = models.CharField(max_length=32)
conformation = models.BooleanField(default=False)
views.py
class CheckAvailability(APIView):
permission_classes = [IsAuthenticated]
def post(self, request):
date = request.data.get('date')
time = request.data.get('time')
location = request.data.get('location')
user = request.user
if date and time and location:
exists, created = Calendar.objects.get_or_create(
user=user,
date=date,
time=time,
location=location
)
if created:
serializer = CalenderSerializer(exists, context={'request': request})
t = threading.Timer(60.0, auto_delete(calendar.id), args=None, kwargs=None)
t.start()
return Response({'response': 'created', 'result': serializer.data, })
else:
return Response({'response': 'Exists'})
def auto_delete(calandar_id):
calendar_id = calandar_id
item = Calendar.objects.get(id=calender_id)
if item.conformation == False:
item.delete()
return Response({'response': 'item deleted'})
创建日历对象后,我想在1分钟后调用auto_delete
函数。调用auto_delete
函数时,post
函数立即起作用。计时器不起作用
谁能帮我解决这个问题?
答案 0 :(得分:1)
根据下面一行,
t = threading.Timer(60.0, auto_delete(calendar.id), args=None, kwargs=None)
您正在立即调用该函数,而没有让线程对其进行处理。像这样将arg
传递给计时器。
t = threading.Timer(60.0, auto_delete, args=[calendar.id], kwargs=None)