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