1# 长时任务开发指导(TaskPool) 2<!--Kit: ArkTS--> 3<!--Subsystem: CommonLibrary--> 4<!--Owner: @lijiamin2025--> 5<!--Designer: @weng-changcheng--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @ge-yafang--> 8 9此处提供使用TaskPool进行长时任务的开发指导,以定期采集传感器数据为例。 10 11## 使用TaskPool进行传感器数据监听 12 131. 导入所需的模块。 14 15 ```ts 16 // Index.ets 17 import { sensor } from '@kit.SensorServiceKit'; 18 import { taskpool } from '@kit.ArkTS'; 19 import { BusinessError, emitter } from '@kit.BasicServicesKit'; 20 ``` 21 222. 定义长时任务,内部监听sensor数据,并通过emitter注册销毁通知。 23 24 ```ts 25 // Index.ets 26 @Concurrent 27 async function SensorListener() : Promise<void> { 28 sensor.on(sensor.SensorId.ACCELEROMETER, (data) => { 29 emitter.emit({ eventId: 0 }, { data: data }); 30 }, { interval: 1000000000 }); 31 32 emitter.on({ eventId: 1 }, () => { 33 sensor.off(sensor.SensorId.ACCELEROMETER) 34 emitter.off(1) 35 }) 36 } 37 ``` 38 393. 给sensor添加ohos.permission.ACCELEROMETER权限。 40 41 ```json 42 // module.json5 43 "requestPermissions": [ 44 { 45 "name": "ohos.permission.ACCELEROMETER" 46 } 47 ] 48 ``` 494. 宿主线程定义注册及销毁的行为。 50 - 注册:发起长时任务,并通过emitter接收监听数据。 51 - 销毁:发送取消传感器监听的事件,并结束长时任务。 52 53 ```ts 54 // Index.ets 55 @Entry 56 @Component 57 struct Index { 58 sensorTask?: taskpool.LongTask 59 60 build() { 61 Column() { 62 Text("Add listener") 63 .id('HelloWorld') 64 .fontSize(50) 65 .fontWeight(FontWeight.Bold) 66 .onClick(() => { 67 this.sensorTask = new taskpool.LongTask(SensorListener); 68 emitter.on({ eventId: 0 }, (data) => { 69 // Do something here 70 console.info(`Receive ACCELEROMETER data: {${data.data?.x}, ${data.data?.y}, ${data.data?.z}}`); 71 }); 72 taskpool.execute(this.sensorTask).then(() => { 73 console.info("Add listener of ACCELEROMETER success"); 74 }).catch((e: BusinessError) => { 75 // Process error 76 }) 77 }) 78 Text("Delete listener") 79 .id('HelloWorld') 80 .fontSize(50) 81 .fontWeight(FontWeight.Bold) 82 .onClick(() => { 83 emitter.emit({ eventId: 1 }); 84 emitter.off(0); 85 if(this.sensorTask != undefined) { 86 taskpool.terminateTask(this.sensorTask); 87 } else { 88 console.error("sensorTask is undefined."); 89 } 90 }) 91 } 92 .height('100%') 93 .width('100%') 94 } 95 } 96 ``` 97 <!-- @[taskpool_listen_sensor_data](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/LongTimeTaskGuide.ets) --> 98 99 100