js-apis-system-timer.md 12.8 KB
Newer Older
E
ester.zhou 已提交
1
# @ohos.systemTimer (System Timer)
E
ester.zhou 已提交
2 3 4

The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services.

E
ester.zhou 已提交
5
> **NOTE**
6 7 8
>
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are system APIs.
E
ester.zhou 已提交
9 10 11 12

## Modules to Import


13
```js
E
ester.zhou 已提交
14 15 16
import systemTimer from '@ohos.systemTimer';
```

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
## Constants

Provides the constants that define the supported timer types.

**System capability**: SystemCapability.MiscServices.Time

| Name               | Type  | Value  | Description                        |
| ------------------- | ------ | ---- | ---------------------------- |
| TIMER_TYPE_REALTIME | number | 1    | CPU time type. (The start time of the timer cannot be later than the current system time.)        |
| TIMER_TYPE_WAKEUP   | number | 2    | Wakeup type.                |
| TIMER_TYPE_EXACT    | number | 4    | Exact type.                |
| TIMER_TYPE_IDLE     | number | 8    | Idle type (not supported currently).|

 ## TimerOptions

Defines the initialization options for **createTimer**.

**System capability**: SystemCapability.MiscServices.Time

| Name     | Type                                         | Mandatory| Description                                                        |
| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| type      | number                                        | Yes  | Timer type.<br>**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)<br>**2**: wakeup type.<br>**4**: exact type.<br>**8**: idle type (not supported currently).|
| repeat    | boolean                                       | Yes  | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer.                       |
| interval  | number                                        | No  | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.|
| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No  | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)|
| callback  | number                                        | Yes  | Callback used to return the timer ID.                            |
E
ester.zhou 已提交
43

44 45

## systemTimer.createTimer
E
ester.zhou 已提交
46 47 48 49 50 51 52 53 54

createTimer(options: TimerOptions, callback: AsyncCallback&lt;number&gt;): void

Creates a timer. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

55 56 57 58
| Name  | Type                         | Mandatory| Description                                                        |
| -------- | ----------------------------- | ---- | ------------------------------------------------------------ |
| options  | [TimerOptions](#timeroptions) | Yes  | Timer initialization options, including the timer type, whether the timer is a repeating timer, interval, and **WantAgent** options.|
| callback | AsyncCallback&lt;number>      | Yes  | Callback used to return the timer ID.                                  |
E
ester.zhou 已提交
59 60 61

**Example**

62
```js
E
ester.zhou 已提交
63
export default {
E
ester.zhou 已提交
64 65 66 67 68 69 70 71 72 73
  systemTimer () {
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat: false
    };
    try {
      systemTimer.createTimer(options, (error, timerId) => {
        if (error) {
          console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
          return;
E
ester.zhou 已提交
74
        }
E
ester.zhou 已提交
75 76 77 78
        console.info(`Succeeded in creating timer. timerId: ${timerId}`);
      });
    } catch(e) {
      console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`);
E
ester.zhou 已提交
79
    }
E
ester.zhou 已提交
80
  }
E
ester.zhou 已提交
81
}
82
```
E
ester.zhou 已提交
83

84
## systemTimer.createTimer
E
ester.zhou 已提交
85 86 87 88 89 90 91 92 93

createTimer(options: TimerOptions): Promise&lt;number&gt;

Creates a timer. This API uses a promise to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

94 95 96
| Name | Type                         | Mandatory| Description                                                        |
| ------- | ----------------------------- | ---- | ------------------------------------------------------------ |
| options | [TimerOptions](#timeroptions) | Yes  | Timer initialization options, including the timer type, whether the timer is a repeating timer, interval, and **WantAgent** options.|
E
ester.zhou 已提交
97 98 99

**Return value**

100 101 102
| Type                 | Description                         |
| --------------------- | ----------------------------- |
| Promise&lt;number&gt; | Promise used to return the timer ID.|
E
ester.zhou 已提交
103 104 105

**Example**

106
```js
E
ester.zhou 已提交
107
export default {
E
ester.zhou 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120
  systemTimer () {
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
    };   
    try {
      systemTimer.createTimer(options).then((timerId) => {
        console.info(`Succeeded in creating timer. timerId: ${timerId}`);
      }).catch((error) => {
        console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
      });
    } catch(e) {
      console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`);
E
ester.zhou 已提交
121
    }
E
ester.zhou 已提交
122
  }
E
ester.zhou 已提交
123
}
124
```
E
ester.zhou 已提交
125

126
## systemTimer.startTimer
E
ester.zhou 已提交
127 128 129 130 131 132 133 134 135

startTimer(timer: number, triggerTime: number, callback: AsyncCallback&lt;void&gt;): void

Starts a timer. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

136 137 138 139 140
| Name     | Type                  | Mandatory| Description                          |
| ----------- | ---------------------- | ---- | ------------------------------ |
| timer       | number                 | Yes  | ID of the timer.                  |
| triggerTime | number                 | Yes  | Time when the timer is triggered, in milliseconds.|
| callback    | AsyncCallback&lt;void> | Yes  | Callback used to return the result.                    |
E
ester.zhou 已提交
141 142 143

**Example**

144
```js
E
ester.zhou 已提交
145
export default {
E
ester.zhou 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158
  async systemTimer () {
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
    }
  let timerId = await systemTimer.createTimer(options);
  let triggerTime = new Date().getTime();
  triggerTime += 3000;
  try {
      systemTimer.startTimer(timerId, triggerTime, (error) => {
        if (error) {
          console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
          return;
E
ester.zhou 已提交
159
        }
E
ester.zhou 已提交
160 161 162 163
        console.info(`Succeeded in starting timer.`);
      });
    } catch(e) {
      console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`);
E
ester.zhou 已提交
164
    }
E
ester.zhou 已提交
165
  }
E
ester.zhou 已提交
166
}
167
```
E
ester.zhou 已提交
168

169
## systemTimer.startTimer
E
ester.zhou 已提交
170 171 172 173 174 175 176 177 178

startTimer(timer: number, triggerTime: number): Promise&lt;void&gt;

Starts a timer. This API uses a promise to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

179 180 181 182 183 184 185 186 187 188
| Name     | Type  | Mandatory| Description                          |
| ----------- | ------ | ---- | ------------------------------ |
| timer       | number | Yes  | ID of the timer.                  |
| triggerTime | number | Yes  | Time when the timer is triggered, in milliseconds.|

**Return value**

| Type          | Description                     |
| -------------- | ------------------------- |
| Promise\<void> | Promise that returns no value.|
E
ester.zhou 已提交
189 190 191

**Example**

192
```js
E
ester.zhou 已提交
193
export default {
E
ester.zhou 已提交
194 195 196 197
  async systemTimer (){
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
E
ester.zhou 已提交
198
    }
E
ester.zhou 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211
    let timerId = await systemTimer.createTimer(options);
    let triggerTime = new Date().getTime();
    triggerTime += 3000;
    try {
      systemTimer.startTimer(timerId, triggerTime).then(() => {
        console.info(`Succeeded in starting timer.`);
         }).catch((error) => {
        console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
      });
    } catch(e) {
      console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`);
    } 
  }
E
ester.zhou 已提交
212
}
213
```
E
ester.zhou 已提交
214

215
## systemTimer.stopTimer
E
ester.zhou 已提交
216 217 218 219 220 221 222 223 224

stopTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void

Stops a timer. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

225 226 227 228
| Name  | Type                  | Mandatory| Description        |
| -------- | ---------------------- | ---- | ------------ |
| timer    | number                 | Yes  | ID of the timer.|
| callback | AsyncCallback&lt;void> | Yes  | Callback used to return the result.  |
E
ester.zhou 已提交
229 230 231

**Example**

232
```js
E
ester.zhou 已提交
233
export default {
E
ester.zhou 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247
  async systemTimer () {
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
    }
    let timerId = await systemTimer.createTimer(options);
    let triggerTime = new Date().getTime();
    triggerTime += 3000;
    systemTimer.startTimer(timerId, triggerTime);
    try {
      systemTimer.stopTimer(timerId, (error) => {
        if (error) {
          console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
          return;
248
        }
E
ester.zhou 已提交
249 250 251 252 253 254
        console.info(`Succeeded in stopping timer.`);
      });
    } catch(e) {
      console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`);
    }
  }
E
ester.zhou 已提交
255
}
256
```
E
ester.zhou 已提交
257

258
## systemTimer.stopTimer
E
ester.zhou 已提交
259 260 261 262 263 264 265 266 267

stopTimer(timer: number): Promise&lt;void&gt;

Stops a timer. This API uses a promise to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

268 269 270 271 272 273 274 275 276
| Name| Type  | Mandatory| Description        |
| ------ | ------ | ---- | ------------ |
| timer  | number | Yes  | ID of the timer.|

**Return value**

| Type          | Description                     |
| -------------- | ------------------------- |
| Promise\<void> | Promise that returns no value.|
E
ester.zhou 已提交
277 278 279

**Example**

280
```js
E
ester.zhou 已提交
281
export default {
E
ester.zhou 已提交
282 283 284 285
  async systemTimer (){
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
E
ester.zhou 已提交
286
    }
E
ester.zhou 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300
    let timerId = await systemTimer.createTimer(options);
    let triggerTime = new Date().getTime();
    triggerTime += 3000;
    systemTimer.startTimer(timerId, triggerTime);
    try {
      systemTimer.stopTimer(timerId).then(() => {
        console.info(`Succeeded in stopping timer.`);
      }).catch((error) => {
        console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
      });
    } catch(e) {
      console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`);
    }
  }
E
ester.zhou 已提交
301
}
302
```
E
ester.zhou 已提交
303

304
## systemTimer.destroyTimer
E
ester.zhou 已提交
305 306 307 308 309 310 311 312 313

destroyTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void

Destroys a timer. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

314 315 316 317
| Name  | Type                  | Mandatory| Description        |
| -------- | ---------------------- | ---- | ------------ |
| timer    | number                 | Yes  | ID of the timer.|
| callback | AsyncCallback&lt;void> | Yes  | Callback used to return the result.  |
E
ester.zhou 已提交
318 319 320

**Example**

321
```js
E
ester.zhou 已提交
322
export default {
E
ester.zhou 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
  async systemTimer () {
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
    }
    let timerId = await systemTimer.createTimer(options);
    let triggerTime = new Date().getTime();
    triggerTime += 3000;
    systemTimer.startTimer(timerId, triggerTime);
    systemTimer.stopTimer(timerId);
    try {
      systemTimer.destroyTimer(timerId, (error) => {
        if (error) {
          console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
          return;
338
        }
E
ester.zhou 已提交
339 340 341 342
        console.info(`Succeeded in destroying timer.`);
      });
    } catch(e) {
      console.info(`Failed to destroying timer. message: ${e.message}, code: ${e.code}`);
E
ester.zhou 已提交
343
    }
E
ester.zhou 已提交
344
  }
E
ester.zhou 已提交
345
}
346
```
E
ester.zhou 已提交
347

348
## systemTimer.destroyTimer
E
ester.zhou 已提交
349 350 351 352 353 354 355 356 357

destroyTimer(timer: number): Promise&lt;void&gt;

Destroys a timer. This API uses a promise to return the result.

**System capability**: SystemCapability.MiscServices.Time

**Parameters**

358 359 360 361 362 363 364 365 366
| Name| Type  | Mandatory| Description        |
| ------ | ------ | ---- | ------------ |
| timer  | number | Yes  | ID of the timer.|

**Return value**

| Type          | Description                     |
| -------------- | ------------------------- |
| Promise\<void> | Promise that returns no value.|
E
ester.zhou 已提交
367 368 369

**Example**

370
```js
E
ester.zhou 已提交
371
export default {
E
ester.zhou 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
  async systemTimer (){
    let options = {
      type: systemTimer.TIMER_TYPE_REALTIME,
      repeat:false
    }
    let timerId = await systemTimer.createTimer(options);
    let triggerTime = new Date().getTime();
    triggerTime += 3000;
    systemTimer.startTimer(timerId, triggerTime);
    systemTimer.stopTimer(timerId);
    try {
      systemTimer.destroyTimer(timerId).then(() => {
         console.info(`Succeeded in destroying timer.`);
      }).catch((error) => {
        console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
      });
    } catch(e) {
      console.info(`Failed to destroying timer. message: ${e.message}, code: ${e.code}`);
E
ester.zhou 已提交
390
    }
E
ester.zhou 已提交
391
  }
E
ester.zhou 已提交
392
}
393
```