feat: 去掉停止按钮,等待中的任务也能暂停

This commit is contained in:
2026-10-25 09:35:39 +08:00
parent d3e553155d
commit 2064519008
6 changed files with 63 additions and 115 deletions
+19 -31
View File
@@ -436,38 +436,24 @@ class JobManager:
return "run"
def pause(self, job: DownloadJob) -> None:
if job.deleting:
raise NqiError("任务正在删除")
if job.stopping or job.cancel_event.is_set():
raise NqiError("任务正在停止")
if job.status != "running" or not job.is_active():
if job.status == "queued":
# 排队中的任务移出队列。还挂着的协程保持停住,点继续时接着用。
job.run_event.clear()
job.status = "paused"
job.message = "已暂停"
job.save()
return
if job.status != "running" or not job.is_active() or job.closing:
raise NqiError("这个任务没有在下载")
job.run_event.clear()
job.status = "paused"
job.message = "已暂停"
job.save()
def request_stop(self, job: DownloadJob) -> None:
if job.closing and job.is_active():
# 上一轮已经在收尾;只取消排队,不再去碰正在关闭的任务。
if job.status == "queued":
job.status = "cancelled"
job.message = "已取消"
job.save()
return
if not job.is_active():
if job.status == "done":
raise NqiError("这个任务已经完成")
job.stopping = False
job.status = "cancelled"
job.message = "已取消"
job.save()
return
job.stopping = True
job.cancel_event.set()
job.run_event.set()
job.status = "running"
job.message = "正在停止"
job.save()
def _queue(self, job: DownloadJob) -> None:
job.status = "queued"
job.message = "等待中"
@@ -568,9 +554,11 @@ class JobManager:
for job in list(self.jobs.values()):
if job.deleting:
continue
if job.status in {"running", "paused"} and not job.is_active():
# 只有标着在下载却没有协程的才算中断。暂停的任务可以没有协程(排队时暂停、登录失效时暂停)。
if job.status == "running" and not job.is_active():
job.status = "cancelled"
job.message = "已中断"
job.stopping = False
job.save()
item = job.snapshot()
if item.get("status") in _FINISHED_STATUSES:
@@ -689,7 +677,7 @@ class JobManager:
duplicate_count=int(data.get("duplicateCount") or 0),
failures=list(data.get("failures") or []),
paused_by=str(data.get("pausedBy") or ""),
stopping=bool(data.get("stopping") or False),
stopping=bool(data.get("stopping") or False) and not interrupted,
failed_tiles=_combine_failed(data.get("failedTiles"), _spool_failed_tiles(path.parent)),
)
except (KeyError, TypeError, ValueError) as exc:
@@ -1054,9 +1042,9 @@ async def run_download(job: DownloadJob) -> None:
await _flush_spool(job, spool)
if not await _sleep_unless_stopped(job, wait):
break
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
except asyncio.CancelledError:
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
raise
except NqiError as exc:
await _mark(job, "error", str(exc) or "下载失败", "error")
@@ -1112,7 +1100,7 @@ async def _run_pass(job: DownloadJob, journal: CsvJournal, columns, spool: IdSpo
grid_size=job.grid_size,
)
if job.cancel_event.is_set():
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
return
service_code = str(layer["serviceCode"])
job.id_field = str(layer.get("originRelatedField") or job.id_field)
@@ -1134,7 +1122,7 @@ async def _run_pass(job: DownloadJob, journal: CsvJournal, columns, spool: IdSpo
job.listing_done = True
if not pending:
if job.cancel_event.is_set():
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
return
await _mark(job, "done", "已完成", "done")
return
@@ -1409,7 +1397,7 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s
raise NqiError("这个地市没有栅格")
unfinished = job.completed + job.failed < job.total or (job.whole_city and not job.listing_done)
if job.cancel_event.is_set() and unfinished:
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
return
if job.failed_tiles:
await _mark(job, "done_with_errors", f"有 {len(job.failed_tiles)} 块区域没读到,点继续重试", "done")
-14
View File
@@ -268,20 +268,6 @@ def _remove_created(data: Path, output: Path) -> None:
shutil.rmtree(output, ignore_errors=True)
@router.post("/jobs/{job_id}/cancel")
async def cancel_job(job_id: str) -> dict:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
try:
state.jobs.request_stop(job)
except NqiError as exc:
raise _bad(str(exc)) from exc
return job.snapshot()
@router.post("/jobs/{job_id}/resume")
async def resume_job(job_id: str) -> dict:
state.require_client()
+6 -3
View File
@@ -477,9 +477,12 @@ def test_only_the_task_limit_runs(tmp_path: Path, monkeypatch):
assert manager.place(second) == "wait"
assert second.status == "queued"
assert second.message == "等待中"
manager.request_stop(second)
assert second.status == "cancelled"
assert second.message == "已取消"
manager.pause(second)
assert second.status == "paused"
assert second.message == "已暂停"
assert manager.queued_jobs() == []
assert len(manager.list_jobs()) == 2
assert second.status == "paused"
first.task = Alive()
manager.pause(first)
+20 -4
View File
@@ -467,7 +467,7 @@ def test_running_count_ignores_paused_and_dead_tasks(tmp_path: Path):
assert manager.running_count() == 0
def test_request_stop_sets_stopping_and_requeue_clears_listing(tmp_path: Path):
def test_requeue_clears_listing_and_queued_job_can_pause(tmp_path: Path):
manager = JobManager()
manager.max_concurrent = 1
city = _job(tmp_path, whole_city=True)
@@ -487,9 +487,25 @@ def test_request_stop_sets_stopping_and_requeue_clears_listing(tmp_path: Path):
manager.jobs[holder.id] = holder
assert manager.place(city) == "wait"
assert city.listing_done is False
manager.request_stop(holder)
assert holder.stopping is True
assert holder.message == "正在停止"
manager.pause(city)
assert city.status == "paused"
assert not city.run_event.is_set()
assert manager.queued_jobs() == []
def test_jobs_paused_by_expiry_stay_paused_until_login(tmp_path: Path):
manager = JobManager()
waiting = _job(tmp_path)
waiting.status = "queued"
manager.jobs[waiting.id] = waiting
manager.suspend_all("登录已失效,请重新登录", mark="expired")
assert waiting.status == "paused"
for item in manager.list_jobs():
if item["id"] == waiting.id:
assert item["status"] == "paused"
assert waiting.status == "paused"
manager.resume_marked("expired")
assert waiting.status == "queued"
def test_active_count_and_sse_removed(tmp_path: Path):