1# 长时任务开发指导(TaskPool)
2
3此处提供使用TaskPool进行长时任务的开发指导,以定期采集传感器数据为例。
4
5## 使用TaskPool进行传感器数据监听
6
71. 导入需要用到的模块。
8
9   ```ts
10   // Index.ets
11   import { sensor } from '@kit.SensorServiceKit';
12   import { taskpool } from '@kit.ArkTS';
13   import { BusinessError, emitter } from '@kit.BasicServicesKit';
14   ```
15
162. 定义长时任务,内部监听sensor数据,并通过emitter注册销毁通知。
17
18   ```ts
19   // Index.ets
20   @Concurrent
21   async function SensorListener() : Promise<void> {
22     sensor.on(sensor.SensorId.ACCELEROMETER, (data) => {
23       emitter.emit({ eventId: 0 }, { data: data });
24     }, { interval: 1000000000 });
25
26     emitter.on({ eventId: 1 }, () => {
27       sensor.off(sensor.SensorId.ACCELEROMETER)
28       emitter.off(1)
29     })
30   }
31   ```
32
333. 宿主线程定义注册及销毁的行为。
34   - 注册:发起长时任务,并通过emitter接收监听数据。
35   - 销毁:发送取消传感器监听的事件,并结束长时任务。
36
37   ```ts
38   // Index.ets
39   @Entry
40   @Component
41   struct Index {
42     sensorTask?: taskpool.LongTask
43
44     build() {
45       Column() {
46         Text("Add listener")
47           .id('HelloWorld')
48           .fontSize(50)
49           .fontWeight(FontWeight.Bold)
50           .onClick(() => {
51             this.sensorTask = new taskpool.LongTask(SensorListener);
52             emitter.on({ eventId: 0 }, (data) => {
53               // Do something here
54               console.info(`Receive ACCELEROMETER data: {${data.data?.x}, ${data.data?.y}, ${data.data?.z}`);
55             });
56             taskpool.execute(this.sensorTask).then(() => {
57               console.info("Add listener of ACCELEROMETER success");
58             }).catch((e: BusinessError) => {
59               // Process error
60             })
61           })
62         Text("Delete listener")
63           .id('HelloWorld')
64           .fontSize(50)
65           .fontWeight(FontWeight.Bold)
66           .onClick(() => {
67             emitter.emit({ eventId: 1 });
68             emitter.off(0);
69             if(this.sensorTask != undefined) {
70               taskpool.terminateTask(this.sensorTask);
71             } else {
72               console.error("sensorTask is undefined.");
73             }
74           })
75       }
76       .height('100%')
77       .width('100%')
78     }
79   }
80   ```
81
82
83