1# 延迟任务调度开发指导 2 3## 场景介绍 4 5应用要执行对实时性要求不高的任务或持久性任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间,[WorkSchedulerExtensionAbility](./workscheduler-extensionability.md)提供了延迟任务回调拓展能力,注册延迟任务后需要实现延迟任务回调拓展能力。延迟任务调度约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束)。 6 7## 接口说明 8 9**表1** workScheduler主要接口 10 11接口名 | 接口描述 12---------------------------------------------------------|----------------------------------------- 13startWork(work: WorkInfo): void; | 延迟调度任务申请 14stopWork(work: WorkInfo, needCancel?: boolean): void; | 延迟调度任务取消 15getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| 获取延迟调度任务状态(Callback形式) 16getWorkStatus(workId: number): Promise\<WorkInfo>; | 获取延迟调度任务状态(Promise形式) 17obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| 获取所有延迟调度任务(Callback形式) 18obtainAllWorks(): Promise<Array\<WorkInfo>>;| 获取所有延迟调度任务(Promise形式) 19stopAndClearWorks(): void;| 停止并清除任务 20isLastWorkTimeOut(workId: number, callback: AsyncCallback\<void>): boolean;| 获取上次任务是否超时(针对RepeatWork,Callback形式) 21isLastWorkTimeOut(workId: number): Promise\<boolean>;| 获取上次任务是否超时(针对RepeatWork,Promise形式) 22 23**表2** WorkInfo包含参数 24 25WorkInfo设置参数约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束) 26 27参数名| 类型 |描述 28---------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- 29workId| number | 延迟任务Id(必填) 30bundleName| string | 延迟任务包名(必填) 31abilityName| string | 延迟任务回调通知的组件名(必填) 32networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | 网络类型 33isCharging| boolean | 是否充电 34chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | 充电类型 35batteryLevel| number | 电量 36batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | 电池状态 37storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |存储状态 38isRepeat| boolean |是否循环任务 39repeatCycleTime| number |循环间隔 40repeatCount | number|循环次数 41parameters | {[key: string]: number | string | boolean} |携带参数信息 42 43**表3** 延迟任务回调接口 44 45接口名 | 接口描述 46---------------------------------------------------------|----------------------------------------- 47onWorkStart(work: WorkInfo): void | 延迟调度任务开始回调 48onWorkStop(work: WorkInfo): void | 延迟调度任务结束回调 49 50### 开发步骤 51 521、导入模块。 53 54注册相关接口包导入: 55```js 56import workScheduler from '@ohos.resourceschedule.workScheduler'; 57``` 58 59回调相关接口包导入: 60```js 61import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; 62``` 63 642、开发对应的ExtensionAbility,用于回调执行具体的延迟任务。关于ExtensionAbility的介绍,参考[ExtensionAbility机制](../application-models/extensionability-overview.md)和[WorkSchedulerExtensionAbility开发指导](./workscheduler-extensionability.md)。 65 66```ts 67import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; 68 69export default class MyExtension extends WorkSchedulerExtensionAbility { 70 onWorkStart(workInfo) { 71 console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); 72 } 73 onWorkStop(workInfo) { 74 console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); 75 } 76} 77``` 78 79 803、注册延迟任务 81 82```ts 83import workScheduler from '@ohos.resourceschedule.workScheduler'; 84 85let workInfo = { 86 workId: 1, 87 batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, 88 isRepeat: false, 89 isPersisted: true, 90 bundleName: "com.example.myapplication", 91 abilityName: "MyExtension", 92 parameters: { 93 mykey0: 1, 94 mykey1: "string value", 95 mykey2: true, 96 mykey3: 1.5 97 } 98} 99try{ 100 workScheduler.startWork(workInfo); 101 console.info('workschedulerLog startWork success'); 102} catch (error) { 103 console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); 104} 105``` 106 107 1084、取消延迟任务 109 110```ts 111import workScheduler from '@ohos.resourceschedule.workScheduler'; 112 113let workInfo = { 114 workId: 1, 115 batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, 116 isRepeat: false, 117 isPersisted: true, 118 bundleName: "com.example.myapplication", 119 abilityName: "MyExtension", 120 parameters: { 121 mykey0: 1, 122 mykey1: "string value", 123 mykey2: true, 124 mykey3: 1.5 125 } 126} 127try{ 128 workScheduler.stopWork(workInfo, false); 129 console.info('workschedulerLog stopWork success'); 130} catch (error) { 131 console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); 132} 133``` 134 135 1365、获取指定延迟任务 137 138```ts 139try{ 140 workScheduler.getWorkStatus(50, (error, res) => { 141 if (error) { 142 console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); 143 } else { 144 for (let item in res) { 145 console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); 146 } 147 } 148 }); 149} catch (error) { 150 console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); 151} 152``` 153 154 1556、获取所有延迟任务 156 157```ts 158try{ 159 workScheduler.obtainAllWorks((error, res) =>{ 160 if (error) { 161 console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); 162 } else { 163 console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); 164 } 165 }); 166} catch (error) { 167 console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); 168} 169``` 170 1717、停止并清除任务 172 173```ts 174try{ 175 workScheduler.stopAndClearWorks(); 176 console.info(`workschedulerLog stopAndClearWorks success`); 177} catch (error) { 178 console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); 179} 180``` 181 1828、判断上次执行是否超时 183 184```ts 185try{ 186 workScheduler.isLastWorkTimeOut(500, (error, res) =>{ 187 if (error) { 188 console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); 189 } else { 190 console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); 191 } 192 }); 193} catch (error) { 194 console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); 195} 196``` 197 198## 相关实例 199 200基于延迟任务调度,有以下相关实例可供参考: 201 202- [`WorkScheduler`:延迟任务调度(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/code/BasicFeature/TaskManagement/WorkScheduler)