from background_task import background from datetime import date, datetime, timedelta from polls.models import Notice, SMSNotifyRecord from polls.utils import sent_sms_notify @background(remove_existing_tasks=True) def process_notify_task(): notices = Notice.objects.filter(is_read=False) for n in notices: two_hours_later = n.added + timedelta(minutes=2) now = datetime.now() if two_hours_later < now: phone = n.user.username today = now.date() hour = now.hour exists = SMSNotifyRecord.objects.filter(phone=phone, added=today).exists() if exists: return if hour < 8 or hour > 17: return print('============',phone, n.type) SMSNotifyRecord.objects.create(phone=phone) sent_sms_notify(phone, n.type)