1# @ohos.systemTimer (系统定时器)(系统接口)
2
3本模块主要由系统定时器功能组成。开发者可以使用定时功能实现定时服务,如闹钟等。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 本模块接口为系统接口。
9
10## 导入模块
11
12
13```ts
14import { systemTimer } from '@kit.BasicServicesKit';
15```
16
17## 常量
18
19支持创建的定时器类型。
20
21**系统能力:** SystemCapability.MiscServices.Time
22
23| 名称                | 类型   | 值   | 说明                                          |
24| ------------------- | ------ | ---- |---------------------------------------------|
25| TIMER_TYPE_REALTIME | number | 1    | 系统启动时间定时器。(定时器启动时间不能晚于当前设置的系统时间)            |
26| TIMER_TYPE_WAKEUP   | number | 2    | 唤醒定时器。(如果未配置为唤醒定时器,则系统处于休眠状态下不会触发,直到退出休眠状态) |
27| TIMER_TYPE_EXACT    | number | 4    | 精准定时器。                                      |
28| TIMER_TYPE_IDLE     | number | 8    | IDLE模式定时器(仅支持系统服务配置,不支持应用配置)。               |
29
30 ## TimerOptions
31
32创建系统定时器的初始化选项。
33
34**系统能力:** SystemCapability.MiscServices.Time
35
36| 名称        | 类型                                          | 必填 | 说明                                                                                                                                                                                                   |
37|-----------| --------------------------------------------- | ---- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
38| type      | number                                        | 是   | 定时器类型,可以使用 '\|' 多选。<br>取值为1,表示为系统启动时间定时器(定时器启动时间不能晚于当前设置的系统时间) ;<br>取值为2,表示为唤醒定时器;<br>取值为4,表示为精准定时器(APP被冻结时,定时器也会被冻结,并且定时器受统一心跳管控,因此即使是精准定时器也不能确保在指定时间点触发);<br>取值为8,表示为IDLE模式定时器(仅支持系统服务配置,不支持应用配置)。 |
39| repeat    | boolean                                       | 是   | 是否为循环定时器。<br>true为循环定时器,false为单次定时器。                                                                                                                                                                 |
40| interval  | number                                        | 否   | 定时器时间间隔。<br>如果是循环定时器,interval值最小为1s,最大为365天,建议interval值不小于5000毫秒;<br>单次定时器interval值为0。                                                                                                               |
41| wantAgent | WantAgent | 否   | 设置通知的WantAgent,定时器到期后通知。(支持拉起应用MainAbility,不支持拉起ServiceAbility。)                                                                                                                                     |
42| callback  | void                                          | 否  | 用户需要执行的回调函数                                                                                                                                                                                          |
43
44
45## systemTimer.createTimer
46
47createTimer(options: TimerOptions, callback: AsyncCallback&lt;number&gt;): void
48
49创建定时器,使用callback异步回调。
50
51**系统能力:** SystemCapability.MiscServices.Time
52
53**参数:**
54
55| 参数名   | 类型                          | 必填 | 说明                                                         |
56| -------- | ----------------------------- | ---- | ------------------------------------------------------------ |
57| options  | [TimerOptions](#timeroptions) | 是   | 创建系统定时器的初始化选项,包括定时器类型、是否循环触发、间隔时间、WantAgent通知机制等。 |
58| callback | AsyncCallback&lt;number>      | 是   | 回调函数,返回定时器的ID。                                   |
59
60**错误码:**
61
62以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
63
64| 错误码ID | 错误信息                                                                                                                                         |
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**示例:**
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 timer. message: ${error.message}, code: ${error.code}`);
82      return;
83    }
84    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
85  });
86} catch(e) {
87  let error = e as BusinessError;
88  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
89}
90```
91
92## systemTimer.createTimer
93
94createTimer(options: TimerOptions): Promise&lt;number&gt;
95
96创建定时器,使用Promise异步回调。
97
98
99**系统能力:** SystemCapability.MiscServices.Time
100
101**参数:**
102
103| 参数名  | 类型                          | 必填 | 说明                                                         |
104| ------- | ----------------------------- | ---- | ------------------------------------------------------------ |
105| options | [TimerOptions](#timeroptions) | 是   | 创建系统定时器的初始化选项,包括定时器类型、是否循环触发、间隔时间、WantAgent通知机制等。 |
106
107**返回值:**
108
109| 类型                  | 说明                          |
110| --------------------- | ----------------------------- |
111| Promise&lt;number&gt; | Promise对象,返回定时器的ID。 |
112
113**错误码:**
114
115以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
116
117| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer. timerId: ${timerId}`);
134  }).catch((error: BusinessError) => {
135    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
136  });
137} catch(e) {
138  let error = e as BusinessError;
139  console.info(`Failed to create 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
147开启定时器,使用callback异步回调。
148
149**系统能力:** SystemCapability.MiscServices.Time
150
151**参数:**
152
153| 参数名      | 类型                   | 必填 | 说明                                                                                                                                                                                                                                                           |
154| ----------- | ---------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
155| timer       | number                 | 是   | 定时器的ID。                                                                                                                                                                                                                                                      |
156| triggerTime | number                 | 是   | 定时器的触发时间,单位:毫秒。<br/>若定时器类型包含了TIMER_TYPE_REALTIME,该triggerTime应为系统启动时间,建议通过[systemDateTime.getUptime(STARTUP)](js-apis-date-time.md#systemdatetimegetuptime10)获取;<br/>若定时器类型不包含TIMER_TYPE_REALTIME,该triggerTime应为墙上时间,建议通过[systemDateTime.getTime()](js-apis-date-time.md#systemdatetimegettime10)获取。 |
157| callback    | AsyncCallback&lt;void> | 是   | 回调函数。                                                                                                                                                                                                                                                        |
158
159**错误码:**
160
161以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
162
163| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer. message: ${error.message}, code: ${error.code}`);
185        return;
186      }
187      console.info(`Succeeded in starting timer.`);
188    });
189    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
190  }).catch((error: BusinessError) => {
191    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
192  });
193} catch(e) {
194  let error = e as BusinessError;
195  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
196}
197```
198
199## systemTimer.startTimer
200
201startTimer(timer: number, triggerTime: number): Promise&lt;void&gt;
202
203开启定时器,使用Promise异步回调。
204
205**系统能力:** SystemCapability.MiscServices.Time
206
207**参数:**
208
209| 参数名      | 类型   | 必填 | 说明                                                                                                                                                                                                                                                           |
210| ----------- | ------ | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
211| timer       | number | 是   | 定时器的ID。                                                                                                                                                                                                                                                      |
212| triggerTime | number | 是   | 定时器的触发时间,单位:毫秒。<br/>若定时器类型包含了TIMER_TYPE_REALTIME,该triggerTime应为系统启动时间,建议通过[systemDateTime.getUptime(STARTUP)](js-apis-date-time.md#systemdatetimegetuptime10)获取;<br/>若定时器类型不包含TIMER_TYPE_REALTIME,该triggerTime应为墙上时间,建议通过[systemDateTime.getTime()](js-apis-date-time.md#systemdatetimegettime10)获取。 |
213
214**返回值:**
215
216| 类型           | 说明                      |
217| -------------- | ------------------------- |
218| Promise\<void> | 无返回结果的Promise对象。 |
219
220**错误码:**
221
222以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
223
224| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer.`);
245    }).catch((error: BusinessError) => {
246      console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
247    });
248    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
249  }).catch((error: BusinessError) => {
250    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
251  });
252} catch(e) {
253  let error = e as BusinessError;
254  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
255}
256```
257
258## systemTimer.stopTimer
259
260stopTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void
261
262停止定时器,使用callback异步回调。
263
264**系统能力:** SystemCapability.MiscServices.Time
265
266**参数:**
267
268| 参数名   | 类型                   | 必填 | 说明         |
269| -------- | ---------------------- | ---- | ------------ |
270| timer    | number                 | 是   | 定时器的ID。 |
271| callback | AsyncCallback&lt;void> | 是   | 回调函数。   |
272
273**错误码:**
274
275以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
276
277| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer. message: ${error.message}, code: ${error.code}`);
300        return;
301      }
302    console.info(`Succeeded in stopping timer.`);
303    });
304    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
305  }).catch((error: BusinessError) => {
306    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
307  });
308} catch(e) {
309  let error = e as BusinessError;
310  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
311}
312```
313
314## systemTimer.stopTimer
315
316stopTimer(timer: number): Promise&lt;void&gt;
317
318停止定时器,使用Promise异步回调。
319
320**系统能力:** SystemCapability.MiscServices.Time
321
322**参数:**
323
324| 参数名 | 类型   | 必填 | 说明         |
325| ------ | ------ | ---- | ------------ |
326| timer  | number | 是   | 定时器的ID。 |
327
328**返回值:**
329
330| 类型           | 说明                      |
331| -------------- | ------------------------- |
332| Promise\<void> | 无返回结果的Promise对象。 |
333
334**错误码:**
335
336以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
337
338| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer.`);
360    }).catch((error: BusinessError) => {
361      console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
362    });
363    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
364  }).catch((error: BusinessError) => {
365    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
366  });
367} catch(e) {
368  let error = e as BusinessError;
369  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
370}
371```
372
373## systemTimer.destroyTimer
374
375destroyTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void
376
377销毁定时器,使用callback异步回调。
378
379**系统能力:** SystemCapability.MiscServices.Time
380
381**参数:**
382
383| 参数名   | 类型                   | 必填 | 说明         |
384| -------- | ---------------------- | ---- | ------------ |
385| timer    | number                 | 是   | 定时器的ID。 |
386| callback | AsyncCallback&lt;void> | 是   | 回调函数。   |
387
388**错误码:**
389
390以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
391
392| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer. message: ${error.message}, code: ${error.code}`);
416        return;
417      }
418    console.info(`Succeeded in destroying timer.`);
419    });
420    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
421  }).catch((error: BusinessError) => {
422    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
423  });
424} catch(e) {
425  let error = e as BusinessError;
426  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
427}
428```
429
430## systemTimer.destroyTimer
431
432destroyTimer(timer: number): Promise&lt;void&gt;
433
434销毁定时器,使用Promise异步回调。
435
436**系统能力:** SystemCapability.MiscServices.Time
437
438**参数:**
439
440| 参数名 | 类型   | 必填 | 说明         |
441| ------ | ------ | ---- | ------------ |
442| timer  | number | 是   | 定时器的ID。 |
443
444**返回值:**
445
446| 类型           | 说明                      |
447| -------------- | ------------------------- |
448| Promise\<void> | 无返回结果的Promise对象。 |
449
450**错误码:**
451
452以下错误码的详细介绍请参见[时间时区错误码](./errorcode-time.md)。
453
454| 错误码ID | 错误信息                                                                                                        |
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**示例:**
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 timer.`);
477    }).catch((error: BusinessError) => {
478      console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
479    });
480    console.info(`Succeeded in creating timer. timerId: ${timerId}`);
481  }).catch((error: BusinessError) => {
482    console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
483  });
484} catch(e) {
485  let error = e as BusinessError;
486  console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
487}
488```