Skip to content

Instantly share code, notes, and snippets.

@Tobi-De
Last active May 11, 2022 08:48
Show Gist options
  • Save Tobi-De/26152fc034ad0a15372d2a977aa9ce82 to your computer and use it in GitHub Desktop.
Save Tobi-De/26152fc034ad0a15372d2a977aa9ce82 to your computer and use it in GitHub Desktop.
showcase django q schedule task setup
# apps.py
from django.apps import AppConfig
class NewsletterConfig(AppConfig):
name = "newsletter"
def ready(self):
from django_q.tasks import schedule
from django.utils import timezone
from dateutil.relativedelta import relativedelta
from django.db import IntegrityError, ProgrammingError, OperationalError
next_run = timezone.now()
schedules = [
{
"func": "newsletter.tasks.send_monthly_reminder",
"name": "Monthly Reminder Mails",
"schedule_type": "M",
"next_run": next_run
},
]
for info in schedules:
try:
schedule(
info["func"],
name=info["name"],
schedule_type=info["schedule_type"],
next_run=info["next_run"]
)
except (ProgrammingError, IntegrityError, OperationalError):
pass
# tasks.py
def send_monthly_reminder():
# messages send before the end of the month to remind user to pay their bill
users = User.objects.filter(Q(is_sub_to_soneb=True) | Q(is_sub_to_sbee=True))
for user in users:
data = {
"user_full_name": user.full_name,
"message_type": "month_reminder",
"month": month_from_date(date.today()),
}
async_task(send_mail, *get_email_content_from_txt(service="bill", data=data),
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[user.email])
async_task(
send_text_message,
get_msg_content_from_txt(service="bill", data=data),
user.full_phone_number,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment