1# Continuous Task Development (TaskPool)
2
3This section describes how to use TaskPool to develop a continuous task. The following uses periodic sensor data collection as an example.
4
5## Using TaskPool to Listen to Sensor Data
6
71. Import the required modules.
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. Defines a long-term task, listens to sensor data internally, and registers a destruction notification through the 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. The host thread defines the registration and destruction behavior.
34   - Registration: Initiate a long-term task and receive listening data through the emitter.
35   - Destroy: Sends the event for canceling the sensor listening and ends the continuous task.
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