PythonIDE Docs
中文
简体中文

background

后台任务、保活与 BGTask 调度。

后台任务:申请延长执行时间、查询剩余时间、调度 BackgroundTasks。

边界:iOS 后台时间有限(begin_task 约 30 秒);schedule_refresh / schedule_processing 需 App 配置对应 BGTask 标识符。不含 background_download 大文件下载。

#模块概览

说明
导入import background
调用时机长任务前 begin_task(),结束 end_task()
适合做什么保存前进度.flush、短同步、注册后台刷新
推荐顺序begin_task() → 工作 → end_task()
状态app_state()active / inactive / background

#快速开始

申请后台时间并查询剩余秒数:

python
import background
import time

if background.begin_task():
    try:
        print("应用状态:", background.app_state())
        print("剩余秒数:", background.remaining_time())
        time.sleep(2)
    finally:
        background.end_task()
else:
    print("无法申请后台任务")

调度后台刷新(需工程内注册 identifier):

python
import background

ok = background.schedule_refresh("com.myapp.refresh")
print("已调度" if ok else "调度失败")

#AppUI 示例

python
import appui
import background

state = appui.State(
    app_state="—",
    remaining="—",
    task="未开始",
)


def refresh_status():
    state.app_state = background.app_state()
    state.remaining = f"{background.remaining_time():.1f}s"


def start_task():
    ok = background.begin_task()
    refresh_status()
    state.task = "进行中" if ok else "申请失败"


def end_task():
    background.end_task()
    refresh_status()
    state.task = "已结束"


def body():
    return appui.NavigationStack(
        appui.Form([
            appui.Section("后台任务", [
                appui.Button("申请延长执行", action=start_task)
                .button_style("bordered_prominent"),
                appui.Button("结束任务", action=end_task),
                appui.Button("刷新状态", action=refresh_status),
            ]),
            appui.Section("状态", [
                appui.LabeledContent("应用状态", value=state.app_state),
                appui.LabeledContent("剩余时间", value=state.remaining),
                appui.LabeledContent("任务", value=state.task),
            ]),
        ]).navigation_title("后台任务")
    )


appui.run(body, state=state)

#API 参考

#速查

API作用
begin_task()申请延长后台时间 → bool
end_task()提前结束
remaining_time()剩余秒数 → float
app_state()active / inactive / background
start_keep_alive() / stop_keep_alive()音频保活(慎用)
schedule_refresh(id, earliest_date=0)调度 BGAppRefreshTask
schedule_processing(id, earliest_date=0, requires_network=False, requires_charging=False)调度 BGProcessingTask

#延长执行

python
background.begin_task()
# ... 短任务 ...
background.end_task()

earliest_date 为 Unix 时间戳;0 表示约 15 分钟后最早触发。

#保活

start_keep_alive() — 启用后台音频会话以延长存活;会消耗电量,仅在有明确需求时使用。


#常见错误

错误写法后果修正
begin_task 后忘记 end_task浪费系统配额try/finally
在后台跑长计算被系统终止拆任务或用 schedule_processing
未注册 BGTask 标识符schedule_* 失败在 Xcode 工程配置
与 background_download 混淆能力不同大文件下载用专用模块

#相关文档

文档用途
background_download后台 URL 下载
audio_session音频会话(保活相关)
notification本地提醒

#预期效果

运行示例后,界面应出现文档描述的目标结果;若与预期不符,先看「失败路径」并按返回值或日志排查。