apscheduler로 휴면계정 삭제하기

김혁준·2023년 6월 29일
0

django

목록 보기
12/18

먼저 함수를 작성하자.

import datetime
from .models import User
def delete_dormant_user():
    dormant_users = User.objects.filter(is_active=False)
    for user in dormant_users:
        last_updated_date = (user.updated_at + datetime.timedelta(hours=9)).date()
        now_date = datetime.date.today()
        dormant_seconds = int((now_date - last_updated_date).total_seconds())
        if dormant_seconds > 604800:
            user.delete()

dormant_users : is_active=False인 휴면유저들.
last_updated_date : 휴면으로 들어간 날짜(+9시간을 해줘야 한국표준시가 된다.)
now_date : 함수 작동되는 날짜.
dormant_seconds: 함수가 작동되는 날짜에서 휴면계정으로 바뀐 날을 빼고 seconds로 바꿔주었다.
dormant_seconds가 7일보다 크면 해당 유저를 삭제한다.

apscheduler에 적용하기.

class Command(BaseCommand):
    help = "Runs delete_dormant_user."

    def start(self, *args, **options):
        scheduler = BackgroundScheduler(
            timezone=settings.TIME_ZONE
        )  # BlockingScheduler를 사용할 수도 있습니다.
        scheduler.add_jobstore(DjangoJobStore(), "default")

        scheduler.add_job(
            delete_dormant_user,
            trigger=CronTrigger(day_of_week="0-6", hour="03", minute="00"),
            id="delete_dormant_user",  # id는 고유해야합니다.
            max_instances=1,
            replace_existing=True,
        )
        logger.info("Added job 'delete_dormant_user'.")

delete_dormant_user 함수를 하루에 한번 새벽3시마다 실행한다!

마지막으로 apps.py에 추가하기.

from django.apps import AppConfig
from django.conf import settings


class UsersConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "users"

    def ready(self):
         if settings.SCHEDULER_DEFAULT:
             from .operator import Command

             Command.start(self)

서버가 시작될때 start함수가 실행된다. 그안에 우리가 만든 함수가 들어있다.

profile
스프링 개발자 지망생입니다

0개의 댓글