Use a different function for getting last run time, avoid async/sync issues

This commit is contained in:
sabaimran 2024-05-02 12:13:45 +05:30
parent 9e8491b814
commit 42e9504ba8
2 changed files with 18 additions and 12 deletions

View file

@ -937,14 +937,6 @@ class AutomationAdapters:
if not automation.id.startswith(f"automation_{user.uuid}_"):
raise ValueError("Invalid automation id")
django_job = DjangoJob.objects.filter(id=automation.id).first()
execution = DjangoJobExecution.objects.filter(job=django_job)
last_run_time = None
if execution.exists():
last_run_time = execution.latest("run_time").run_time
automation_metadata = json.loads(automation.name)
crontime = automation_metadata["crontime"]
timezone = automation.next_run_time.strftime("%Z")
@ -957,9 +949,25 @@ class AutomationAdapters:
"schedule": schedule,
"crontime": crontime,
"next": automation.next_run_time.strftime("%Y-%m-%d %I:%M %p %Z"),
"last_run": last_run_time.strftime("%Y-%m-%d %I:%M %p %Z") if last_run_time else None,
}
@staticmethod
def get_job_last_run(user: KhojUser, automation: Job):
# Perform validation checks
# Check if user is allowed to delete this automation id
if not automation.id.startswith(f"automation_{user.uuid}_"):
raise ValueError("Invalid automation id")
django_job = DjangoJob.objects.filter(id=automation.id).first()
execution = DjangoJobExecution.objects.filter(job=django_job, status="Executed")
last_run_time = None
if execution.exists():
last_run_time = execution.latest("run_time").run_time
return last_run_time.strftime("%Y-%m-%d %I:%M %p %Z") if last_run_time else None
@staticmethod
def get_automations_metadata(user: KhojUser):
for automation in AutomationAdapters.get_automations(user):

View file

@ -891,9 +891,7 @@ def scheduled_chat(
if job_id:
# Get the job object and check whether the time is valid for it to run. This helps avoid race conditions that cause the same job to be run multiple times.
job = AutomationAdapters.get_automation(user, job_id)
metadata = AutomationAdapters.get_automation_metadata(user, job)
last_run_time = metadata.get("last_run", None)
last_run_time = AutomationAdapters.get_job_last_run(user, job)
# Convert last_run_time from %Y-%m-%d %I:%M %p %Z to datetime object
if last_run_time: