🐛 修复定时任务执行耗时显示为0的问题

- 启动监控线程等待所有任务完成后再更新日志
- 通过参数传递避免闭包问题
- 耗时现在正确反映实际任务执行时间

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-10 22:09:30 +08:00
parent d811fc7c56
commit e07544784c

38
app.py
View File

@@ -2995,6 +2995,7 @@ def scheduled_task_worker():
started_count = 0 started_count = 0
skipped_count = 0 skipped_count = 0
task_threads = [] # 收集所有启动的任务线程
for account_id in account_ids: for account_id in account_ids:
if user_id not in user_accounts: if user_id not in user_accounts:
@@ -3019,6 +3020,7 @@ def scheduled_task_worker():
) )
thread.start() thread.start()
active_tasks[account_id] = thread active_tasks[account_id] = thread
task_threads.append(thread)
started_count += 1 started_count += 1
socketio.emit('account_update', account.to_dict(), room=f'user_{user_id}') socketio.emit('account_update', account.to_dict(), room=f'user_{user_id}')
@@ -3026,18 +3028,40 @@ def scheduled_task_worker():
# 更新最后执行时间 # 更新最后执行时间
database.update_schedule_last_run(schedule_id) database.update_schedule_last_run(schedule_id)
# 更新执行日志 print(f"[用户定时任务] 已启动 {started_count} 个账号,跳过 {skipped_count} 个账号")
execution_duration = int(time_mod.time() - execution_start_time)
# 启动监控线程,等待所有任务完成后更新日志
def wait_and_update_log(threads, start_time, lid, total, success, sid):
for t in threads:
t.join() # 等待每个任务完成
execution_duration = int(time_mod.time() - start_time)
database.update_schedule_execution_log( database.update_schedule_execution_log(
log_id, lid,
total_accounts=len(account_ids), total_accounts=total,
success_accounts=started_count, success_accounts=success,
failed_accounts=len(account_ids) - started_count, failed_accounts=total - success,
duration_seconds=execution_duration, duration_seconds=execution_duration,
status='completed' status='completed'
) )
print(f"[用户定时任务] 任务#{sid}执行完成,耗时{execution_duration}")
print(f"[用户定时任务] 已启动 {started_count} 个账号,跳过 {skipped_count} 个账号") if task_threads:
monitor_thread = threading.Thread(
target=wait_and_update_log,
args=(task_threads, execution_start_time, log_id, len(account_ids), started_count, schedule_id),
daemon=True
)
monitor_thread.start()
else:
# 没有启动任何任务,直接更新日志
database.update_schedule_execution_log(
log_id,
total_accounts=len(account_ids),
success_accounts=0,
failed_accounts=len(account_ids),
duration_seconds=0,
status='completed'
)
if started_count == 0 and len(account_ids) > 0: if started_count == 0 and len(account_ids) > 0:
print(f"[用户定时任务] ⚠️ 警告所有账号都被跳过了请检查user_accounts状态") print(f"[用户定时任务] ⚠️ 警告所有账号都被跳过了请检查user_accounts状态")