mirror of https://github.com/jumpserver/jumpserver
perf: Optimize average_time_cost calculation in job model
parent
583486e26e
commit
eafb5ecfb3
|
@ -9,7 +9,8 @@ from datetime import timedelta
|
||||||
from celery import current_task
|
from celery import current_task
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.db.models import Q
|
from django.db.models import Q, Avg, F, FloatField
|
||||||
|
from django.db.models.functions import Coalesce, Now, Extract
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
@ -188,11 +189,17 @@ class Job(JMSOrgBaseModel, PeriodTaskModelMixin):
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def average_time_cost(self):
|
def average_time_cost(self):
|
||||||
total_cost = 0
|
executions = self.executions.filter(status__in=['success', 'failed'])
|
||||||
finished_count = self.executions.filter(status__in=['success', 'failed']).count()
|
if not executions.exists():
|
||||||
for execution in self.executions.filter(status__in=['success', 'failed']).all():
|
return 0
|
||||||
total_cost += execution.time_cost
|
average = executions.annotate(
|
||||||
return total_cost / finished_count if finished_count else 0
|
time_cost=Coalesce(F('date_finished'), Now()) - F('date_start')
|
||||||
|
).annotate(
|
||||||
|
time_cost_seconds=Extract('time_cost', 'epoch')
|
||||||
|
).aggregate(
|
||||||
|
avg_time=Avg('time_cost_seconds')
|
||||||
|
)['avg_time']
|
||||||
|
return average if average is not None else 0
|
||||||
|
|
||||||
def get_register_task(self):
|
def get_register_task(self):
|
||||||
from ..tasks import run_ops_job
|
from ..tasks import run_ops_job
|
||||||
|
|
Loading…
Reference in New Issue