38 lines
1.5 KiB
Python
38 lines
1.5 KiB
Python
import time
|
|
from datetime import timedelta
|
|
from django.core.management.base import BaseCommand
|
|
from django.db import close_old_connections
|
|
from django.utils import timezone
|
|
from system_manage.models.ai_hub import AITask
|
|
from system_manage.ai_hub_worker import claim, execute
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Run the isolated AI hub task consumer (does not run migrations).'
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument('--once', action='store_true')
|
|
parser.add_argument('--recover', action='store_true', help='Mark running tasks older than 30 minutes failed')
|
|
|
|
def handle(self, *args, **options):
|
|
if options['recover']:
|
|
AITask.objects.filter(status='RUNNING', updated_at__lt=timezone.now() - timedelta(minutes=30)).update(
|
|
status='FAILED', error='执行中断,请重试', finished_at=timezone.now())
|
|
next_cleanup = time.monotonic() + 86400
|
|
while True:
|
|
close_old_connections()
|
|
if time.monotonic() >= next_cleanup:
|
|
from system_manage.ai_hub_assets import cleanup
|
|
try:
|
|
cleanup(apply=True)
|
|
except Exception:
|
|
self.stderr.write('图片缓存清理失败,将于下次重试')
|
|
next_cleanup = time.monotonic() + 86400
|
|
task = claim()
|
|
if task:
|
|
execute(task)
|
|
if options['once']:
|
|
return
|
|
if not task:
|
|
time.sleep(2)
|