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