• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.systemTimer (System Timer) (System API)
2<!--Kit: Basic Services Kit-->
3<!--Subsystem: Time-->
4<!--Owner: @huaxin05-->
5<!--Designer: @hu-kai45-->
6<!--Tester: @murphy1984-->
7<!--Adviser: @zhang_yixin13-->
8
9The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services.
10
11> **NOTE**
12>
13> - 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.
14> - The APIs provided by this module are system APIs.
15
16## Modules to Import
17
18
19```ts
20import { systemTimer } from '@kit.BasicServicesKit';
21```
22
23## Constants
24
25Provides the constants that define the supported timer types.
26
27**System capability**: SystemCapability.MiscServices.Time
28
29| Name               | Type  | Value  | Description                                         |
30| ------------------- | ------ | ---- |---------------------------------------------|
31| TIMER_TYPE_REALTIME | number | 1    | CPU time type. (The start time of the timer cannot be later than the current system time.)|
32| TIMER_TYPE_WAKEUP   | number | 2    | Wakeup type. (If the wakeup type is not set, the system does not wake up until it exits the sleep state.)|
33| TIMER_TYPE_EXACT    | number | 4    | Exact type. (If the system time is changed, the offset may be 1s at most.)|
34| TIMER_TYPE_IDLE     | number | 8    | Idle timer type (supported only for system services).|
35
36 ## TimerOptions
37
38Defines the initialization options for **createTimer**.
39
40**System capability**: SystemCapability.MiscServices.Time
41
42| Name       | Type                                         | Mandatory| Description                                                                                                                                                                                                  |
43|-----------| --------------------------------------------- | ---- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
44| type      | number                                        | Yes  | Timer types. Use pipe (\|) symbol|to combine two or more types.<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. (If an application is frozen, the timer is also frozen. In addition, the timer is controlled by a unified heartbeat. Therefore, even a timer of the exact type cannot be triggered at specified time.)<br>**8**: idle timer type (supported only for system services, but not applications).|
45| 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.                                                                                                                                                                |
46| autoRestore<sup>15+</sup> | boolean                                     | No  | Whether the timer is restored after the device is restarted.<br>The value **true** means that the timer is restored after the restart, and the value **false** means the opposite.<br>This parameter can be set to **true** only for timers that are not of the **TIMER_TYPE_REALTIME** type and have **wantAgent** configured.                                                                                                     |                                               |     |                                                                                                                                                                                                      |
47| name<sup>15+</sup> | string | No| Timer name, with a maximum length of 64 bytes.<br>A UID cannot contain two timers with the same name. If a timer with the same name as an existing timer is created, the existing timer is destroyed.|
48| interval  | number                                        | No  | Interval between two consecutive timers, in milliseconds. Default value: **0**.<br>For a repeating timer, the minimum value of **interval** is 1s and the maximum value is 365 days. It is recommended that the value be greater than or equal to 5000 ms.<br>For a one-shot timer, the value is **0**.                                                                                                              |
49| wantAgent | WantAgent | No  | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)                                                                                                                                    |
50| callback  | void                                          | No | Callback to be executed by the user.                                                                                                                                                                                         |
51
52
53## systemTimer.createTimer
54
55createTimer(options: TimerOptions, callback: AsyncCallback&lt;number&gt;): void
56
57Creates a timer. This API uses an asynchronous callback to return the result.
58
59**NOTE**<br>This function must be used together with [systemTimer.destroyTimer](#systemtimerdestroytimer). Otherwise, memory leakage occurs.
60
61**System capability**: SystemCapability.MiscServices.Time
62
63**Parameters**
64
65| Name  | Type                         | Mandatory| Description                                                        |
66| -------- | ----------------------------- | ---- | ------------------------------------------------------------ |
67| options  | [TimerOptions](#timeroptions) | Yes  | Timer initialization options, including the timer type, whether the timer is a repeating timer, interval, and **WantAgent** options.|
68| callback | AsyncCallback&lt;number>      | Yes  | Callback used to return the timer ID.                                  |
69
70**Error codes**
71
72For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
73
74| ID| Error Message                                                                                                                                        |
75|-------|----------------------------------------------------------------------------------------------------------------------------------------------|
76| 202   | Permission verification failed. A non-system application calls a system API.                                                                 |
77| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
78
79**Example**
80
81```ts
82import { BusinessError } from '@kit.BasicServicesKit';
83
84let options: systemTimer.TimerOptions = {
85  type: systemTimer.TIMER_TYPE_REALTIME,
86  repeat: false
87};
88try {
89  systemTimer.createTimer(options, (error: BusinessError, timerId: Number) => {
90    if (error) {
91      console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
92      return;
93    }
94    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
95  });
96} catch(e) {
97  let error = e as BusinessError;
98  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
99}
100```
101
102## systemTimer.createTimer
103
104createTimer(options: TimerOptions): Promise&lt;number&gt;
105
106Creates a timer. This API uses a promise to return the timer ID.
107
108**NOTE**<br>This function must be used together with [systemTimer.destroyTimer](#systemtimerdestroytimer). Otherwise, memory leakage occurs.
109
110**System capability**: SystemCapability.MiscServices.Time
111
112**Parameters**
113
114| Name | Type                         | Mandatory| Description                                                        |
115| ------- | ----------------------------- | ---- | ------------------------------------------------------------ |
116| options | [TimerOptions](#timeroptions) | Yes  | Timer initialization options, including the timer type, whether the timer is a repeating timer, interval, and **WantAgent** options.|
117
118**Return value**
119
120| Type                 | Description                         |
121| --------------------- | ----------------------------- |
122| Promise&lt;number&gt; | Promise used to return the timer ID.|
123
124**Error codes**
125
126For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
127
128| ID| Error Message                                                                                                       |
129|-------|-------------------------------------------------------------------------------------------------------------|
130| 202   | Permission verification failed. A non-system application calls a system API.                                |
131| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
132
133**Example**
134
135```ts
136import { BusinessError } from '@kit.BasicServicesKit';
137
138let options: systemTimer.TimerOptions = {
139  type: systemTimer.TIMER_TYPE_REALTIME,
140  repeat:false
141};
142try {
143  systemTimer.createTimer(options).then((timerId: Number) => {
144    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
145  }).catch((error: BusinessError) => {
146    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
147  });
148} catch(e) {
149  let error = e as BusinessError;
150  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
151}
152```
153
154## systemTimer.startTimer
155
156startTimer(timer: number, triggerTime: number, callback: AsyncCallback&lt;void&gt;): void
157
158Starts a timer. This API uses an asynchronous callback to return the result.
159
160**System capability**: SystemCapability.MiscServices.Time
161
162**Parameters**
163
164| Name     | Type                  | Mandatory| Description                                                                                                                                                                                                                                                          |
165| ----------- | ---------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
166| timer       | number                 | Yes  | ID of the timer.                                                                                                                                                                                                                                                     |
167| triggerTime | number                 | Yes  | Time when the timer is triggered, in milliseconds.<br>If **TIMER_TYPE_REALTIME** is set as the timer type, the value of **triggerTime** is the system startup time, which can be obtained by calling [systemDateTime.getUptime(STARTUP)](js-apis-date-time.md#systemdatetimegetuptime10).<br>If **TIMER_TYPE_REALTIME** is not set, the value of **triggerTime** is the wall time, which can be obtained by calling [systemDateTime.getTime()](js-apis-date-time.md#systemdatetimegettime10).|
168| callback    | AsyncCallback&lt;void> | Yes  | Callback used to return the result.                                                                                                                                                                                                                                                       |
169
170**Error codes**
171
172For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
173
174| ID| Error Message                                                                                                       |
175|-------|-------------------------------------------------------------------------------------------------------------|
176| 202   | Permission verification failed. A non-system application calls a system API.                                |
177| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
178
179**Example**
180
181```ts
182import { BusinessError } from '@kit.BasicServicesKit';
183
184let options: systemTimer.TimerOptions = {
185  type: systemTimer.TIMER_TYPE_REALTIME,
186  repeat:false
187}
188let triggerTime = new Date().getTime();
189triggerTime += 3000;
190
191try {
192  systemTimer.createTimer(options).then((timerId: number) => {
193    systemTimer.startTimer(timerId, triggerTime, (error: BusinessError) => {
194      if (error) {
195        console.error(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
196        return;
197      }
198      console.info(`Succeeded in starting the timer.`);
199    });
200    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
201  }).catch((error: BusinessError) => {
202    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
203  });
204} catch(e) {
205  let error = e as BusinessError;
206  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
207}
208```
209
210## systemTimer.startTimer
211
212startTimer(timer: number, triggerTime: number): Promise&lt;void&gt;
213
214Starts a timer. This API uses a promise to return the result.
215
216**System capability**: SystemCapability.MiscServices.Time
217
218**Parameters**
219
220| Name     | Type  | Mandatory| Description                                                                                                                                                                                                                                                          |
221| ----------- | ------ | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
222| timer       | number | Yes  | ID of the timer.                                                                                                                                                                                                                                                     |
223| triggerTime | number | Yes  | Time when the timer is triggered, in milliseconds.<br>If **TIMER_TYPE_REALTIME** is set as the timer type, the value of **triggerTime** is the system startup time, which can be obtained by calling [systemDateTime.getUptime(STARTUP)](js-apis-date-time.md#systemdatetimegetuptime10).<br>If **TIMER_TYPE_REALTIME** is not set, the value of **triggerTime** is the wall time, which can be obtained by calling [systemDateTime.getTime()](js-apis-date-time.md#systemdatetimegettime10).|
224
225**Return value**
226
227| Type          | Description                     |
228| -------------- | ------------------------- |
229| Promise\<void> | Promise that returns no value.|
230
231**Error codes**
232
233For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
234
235| ID| Error Message                                                                                                       |
236|-------|-------------------------------------------------------------------------------------------------------------|
237| 202   | Permission verification failed. A non-system application calls a system API.                                |
238| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
239
240**Example**
241
242```ts
243import { BusinessError } from '@kit.BasicServicesKit';
244
245let options: systemTimer.TimerOptions = {
246  type: systemTimer.TIMER_TYPE_REALTIME,
247  repeat:false
248}
249let triggerTime = new Date().getTime();
250triggerTime += 3000;
251
252try {
253  systemTimer.createTimer(options).then((timerId: number) => {
254    systemTimer.startTimer(timerId, triggerTime).then(() => {
255      console.info(`Succeeded in starting the timer.`);
256    }).catch((error: BusinessError) => {
257      console.error(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
258    });
259    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
260  }).catch((error: BusinessError) => {
261    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
262  });
263} catch(e) {
264  let error = e as BusinessError;
265  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
266}
267```
268
269## systemTimer.stopTimer
270
271stopTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void
272
273Stops the timer. This API uses an asynchronous callback to return the result.
274
275**System capability**: SystemCapability.MiscServices.Time
276
277**Parameters**
278
279| Name  | Type                  | Mandatory| Description        |
280| -------- | ---------------------- | ---- | ------------ |
281| timer    | number                 | Yes  | ID of the timer.|
282| callback | AsyncCallback&lt;void> | Yes  | Callback used to return the result.  |
283
284**Error codes**
285
286For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
287
288| ID| Error Message                                                                                                       |
289|-------|-------------------------------------------------------------------------------------------------------------|
290| 202   | Permission verification failed. A non-system application calls a system API.                                |
291| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
292
293**Example**
294
295```ts
296import { BusinessError } from '@kit.BasicServicesKit';
297
298let options: systemTimer.TimerOptions = {
299  type: systemTimer.TIMER_TYPE_REALTIME,
300  repeat:false
301}
302let triggerTime = new Date().getTime();
303triggerTime += 3000;
304
305try {
306  systemTimer.createTimer(options).then((timerId: number) => {
307    systemTimer.startTimer(timerId, triggerTime);
308    systemTimer.stopTimer(timerId, (error: BusinessError) => {
309      if (error) {
310        console.error(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
311        return;
312      }
313    console.info(`Succeeded in stopping the timer.`);
314    });
315    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
316  }).catch((error: BusinessError) => {
317    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
318  });
319} catch(e) {
320  let error = e as BusinessError;
321  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
322}
323```
324
325## systemTimer.stopTimer
326
327stopTimer(timer: number): Promise&lt;void&gt;
328
329Stops a timer. This API uses a promise to return the result.
330
331**System capability**: SystemCapability.MiscServices.Time
332
333**Parameters**
334
335| Name| Type  | Mandatory| Description        |
336| ------ | ------ | ---- | ------------ |
337| timer  | number | Yes  | ID of the timer.|
338
339**Return value**
340
341| Type          | Description                     |
342| -------------- | ------------------------- |
343| Promise\<void> | Promise that returns no value.|
344
345**Error codes**
346
347For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
348
349| ID| Error Message                                                                                                       |
350|-------|-------------------------------------------------------------------------------------------------------------|
351| 202   | Permission verification failed. A non-system application calls a system API.                                |
352| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
353
354**Example**
355
356```ts
357import { BusinessError } from '@kit.BasicServicesKit';
358
359let options: systemTimer.TimerOptions = {
360  type: systemTimer.TIMER_TYPE_REALTIME,
361  repeat:false
362}
363let triggerTime = new Date().getTime();
364triggerTime += 3000;
365
366try {
367  systemTimer.createTimer(options).then((timerId: number) => {
368    systemTimer.startTimer(timerId, triggerTime);
369    systemTimer.stopTimer(timerId).then(() => {
370      console.info(`Succeeded in stopping the timer.`);
371    }).catch((error: BusinessError) => {
372      console.error(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
373    });
374    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
375  }).catch((error: BusinessError) => {
376    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
377  });
378} catch(e) {
379  let error = e as BusinessError;
380  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
381}
382```
383
384## systemTimer.destroyTimer
385
386destroyTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void
387
388Destroys a timer. This API uses an asynchronous callback to return the result.
389
390**System capability**: SystemCapability.MiscServices.Time
391
392**Parameters**
393
394| Name  | Type                  | Mandatory| Description        |
395| -------- | ---------------------- | ---- | ------------ |
396| timer    | number                 | Yes  | ID of the timer.|
397| callback | AsyncCallback&lt;void> | Yes  | Callback used to return the result.  |
398
399**Error codes**
400
401For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
402
403| ID| Error Message                                                                                                       |
404|-------|-------------------------------------------------------------------------------------------------------------|
405| 202   | Permission verification failed. A non-system application calls a system API.                                |
406| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
407
408**Example**
409
410```ts
411import { BusinessError } from '@kit.BasicServicesKit';
412
413let options: systemTimer.TimerOptions = {
414  type: systemTimer.TIMER_TYPE_REALTIME,
415  repeat:false
416}
417let triggerTime = new Date().getTime();
418triggerTime += 3000;
419
420try {
421  systemTimer.createTimer(options).then((timerId: number) => {
422    systemTimer.startTimer(timerId, triggerTime);
423    systemTimer.stopTimer(timerId);
424    systemTimer.destroyTimer(timerId, (error: BusinessError) => {
425      if (error) {
426        console.error(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
427        return;
428      }
429    console.info(`Succeeded in destroying the timer.`);
430    });
431    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
432  }).catch((error: BusinessError) => {
433    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
434  });
435} catch(e) {
436  let error = e as BusinessError;
437  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
438}
439```
440
441## systemTimer.destroyTimer
442
443destroyTimer(timer: number): Promise&lt;void&gt;
444
445Destroys a timer. This API uses a promise to return the result.
446
447**System capability**: SystemCapability.MiscServices.Time
448
449**Parameters**
450
451| Name| Type  | Mandatory| Description        |
452| ------ | ------ | ---- | ------------ |
453| timer  | number | Yes  | ID of the timer.|
454
455**Return value**
456
457| Type          | Description                     |
458| -------------- | ------------------------- |
459| Promise\<void> | Promise that returns no value.|
460
461**Error codes**
462
463For details about the error codes, see [Time and Time Zone Service Error Codes](./errorcode-time.md).
464
465| ID| Error Message                                                                                                       |
466|-------|-------------------------------------------------------------------------------------------------------------|
467| 202   | Permission verification failed. A non-system application calls a system API.                                |
468| 401   | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
469
470**Example**
471
472```ts
473import { BusinessError } from '@kit.BasicServicesKit';
474
475let options: systemTimer.TimerOptions = {
476  type: systemTimer.TIMER_TYPE_REALTIME,
477  repeat:false
478}
479let triggerTime = new Date().getTime();
480triggerTime += 3000;
481
482try {
483  systemTimer.createTimer(options).then((timerId: number) => {
484    systemTimer.startTimer(timerId, triggerTime);
485    systemTimer.stopTimer(timerId);
486    systemTimer.destroyTimer(timerId).then(() => {
487      console.info(`Succeeded in destroying the timer.`);
488    }).catch((error: BusinessError) => {
489      console.error(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
490    });
491    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
492  }).catch((error: BusinessError) => {
493    console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
494  });
495} catch(e) {
496  let error = e as BusinessError;
497  console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
498}
499```
500