1 回答
TA贡献1806条经验 获得超8个赞
将 django-celery-beat 用于定期任务会很好:http: //docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers
以此为例
将此视为您的用户models.py。您在这里需要的是一个过期字段,cronjob 在删除它之前会对其进行检查。
models.py
class Foo(models.model):
UserId= models.CharField(max_length=40, unique=True) #user pk here
expiration_date = models.DateTimeField() # you would set the time here
views.py
import datetime
from django.utils import timezone
def add_foo(instance):
# Create an instance of foo with expiration date now + one day
objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))
path = str(os.getcwd())
try:
pathdl = f"{path}\\data\\media\\{instance.username}"
shutil.rmtree(pathdl)
User.objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))
except Exception:
print(Exception)
post_delete.connect(delete_files, sender=User)
tasks.py
from celery.schedules import crontab
from celery.task import periodic_task
from django.utils import timezone
@periodic_task(run_every=crontab(minute='*/5'))
def delete_old_foos():
# Query all the expired date in our database
userMedia = Users.objects.all()
#Or get a specific user id to delete their file
# Iterate through them
for file in userMedia :
# If the expiration date is bigger than now delete it
if file.expiration_date < timezone.now():
file.delete()
# log deletion
return "completed deleting file at {}".format(timezone.now())
当然,你也可以将这个想法融入到任何你想解决这个问题的方式中。
添加回答
举报
