openharmony 鸿蒙 js-apis-system-timer-sys

2025-06-12 浏览 (1)

@ohos.systemTimer (System Timer) (System API)

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

NOTE

  • The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
  • The APIs provided by this module are system APIs.

Modules to Import

import { systemTimer } from '@kit.BasicServicesKit';

Constants

Provides the constants that define the supported timer types.

System capability: SystemCapability.MiscServices.Time

NameTypeValueDescription
TIMER_TYPE_REALTIMEnumber1CPU time type. (The start time of the timer cannot be later than the current system time.)
TIMER_TYPE_WAKEUPnumber2Wakeup type. (If the wakeup type is not set, the system does not wake up until it exits the sleep state.)
TIMER_TYPE_EXACTnumber4Exact type. (If the system time is changed, the offset may be 1s at most.)
TIMER_TYPE_IDLEnumber8Idle timer type (supported only for system services).

TimerOptions

Defines the initialization options for createTimer.

System capability: SystemCapability.MiscServices.Time

NameTypeMandatoryDescription
typenumberYesTimer types. Use pipe (|) symbol to combine two or more types.
1: CPU time type. (The start time of the timer cannot be later than the current system time.)
2: wakeup type.
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.)
8: idle timer type (supported only for system services, but not applications).
repeatbooleanYesWhether 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.
autoRestore15+booleanNoWhether the timer is restored after the device is restarted.
The value true means that the timer is restored after the restart, and the value false means the opposite.
This parameter can be set to true only for timers that are not of the TIMER_TYPE_REALTIME type and have wantAgent configured.
name15+stringNoTimer name, with a maximum length of 64 bytes.
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.
intervalnumberNoRepeat interval.
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.
For a one-shot timer, the value is 0.
wantAgentWantAgentNoWantAgent object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)
callbackvoidNoCallback to be executed by the user.

systemTimer.createTimer

createTimer(options: TimerOptions, callback: AsyncCallback<number>): void

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

NOTE
This function must be used together with systemTimer.destroyTimer. Otherwise, memory leakage occurs.

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
optionsTimerOptionsYesTimer initialization options, including the timer type, whether the timer is a repeating timer, interval, and WantAgent options.
callbackAsyncCallback<number>YesCallback used to return the timer ID.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat: false
};
try {
  systemTimer.createTimer(options, (error: BusinessError, timerId: Number) => {
    if (error) {
      console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
      return;
    }
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.createTimer

createTimer(options: TimerOptions): Promise<number>

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

NOTE
This function must be used together with systemTimer.destroyTimer. Otherwise, memory leakage occurs.

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
optionsTimerOptionsYesTimer initialization options, including the timer type, whether the timer is a repeating timer, interval, and WantAgent options.

Return value

TypeDescription
Promise<number>Promise used to return the timer ID.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
};
try {
  systemTimer.createTimer(options).then((timerId: Number) => {
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.startTimer

startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void

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

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
timernumberYesID of the timer.
triggerTimenumberYesTime when the timer is triggered, in milliseconds.
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).
If TIMER_TYPE_REALTIME is not set, the value of triggerTime is the wall time, which can be obtained by calling systemDateTime.getTime().
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
}
let triggerTime = new Date().getTime();
triggerTime += 3000;

try {
  systemTimer.createTimer(options).then((timerId: number) => {
    systemTimer.startTimer(timerId, triggerTime, (error: BusinessError) => {
      if (error) {
        console.info(`Failed to start the timer. Message: ${error.message}, code: ${error.code}`);
        return;
      }
      console.info(`Succeeded in starting the timer.`);
    });
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.startTimer

startTimer(timer: number, triggerTime: number): Promise<void>

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

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
timernumberYesID of the timer.
triggerTimenumberYesTime when the timer is triggered, in milliseconds.
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).
If TIMER_TYPE_REALTIME is not set, the value of triggerTime is the wall time, which can be obtained by calling systemDateTime.getTime().

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
}
let triggerTime = new Date().getTime();
triggerTime += 3000;

try {
  systemTimer.createTimer(options).then((timerId: number) => {
    systemTimer.startTimer(timerId, triggerTime).then(() => {
      console.info(`Succeeded in starting the timer.`);
    }).catch((error: BusinessError) => {
      console.info(`Failed to start the timer. Message: ${error.message}, code: ${error.code}`);
    });
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.stopTimer

stopTimer(timer: number, callback: AsyncCallback<void>): void

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

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
timernumberYesID of the timer.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
}
let triggerTime = new Date().getTime();
triggerTime += 3000;

try {
  systemTimer.createTimer(options).then((timerId: number) => {
    systemTimer.startTimer(timerId, triggerTime);
    systemTimer.stopTimer(timerId, (error: BusinessError) => {
      if (error) {
        console.info(`Failed to stop the timer. Message: ${error.message}, code: ${error.code}`);
        return;
      }
    console.info(`Succeeded in stopping the timer.`);
    });
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.stopTimer

stopTimer(timer: number): Promise<void>

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

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
timernumberYesID of the timer.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
}
let triggerTime = new Date().getTime();
triggerTime += 3000;

try {
  systemTimer.createTimer(options).then((timerId: number) => {
    systemTimer.startTimer(timerId, triggerTime);
    systemTimer.stopTimer(timerId).then(() => {
      console.info(`Succeeded in stopping the timer.`);
    }).catch((error: BusinessError) => {
      console.info(`Failed to stop the timer. Message: ${error.message}, code: ${error.code}`);
    });
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.destroyTimer

destroyTimer(timer: number, callback: AsyncCallback<void>): void

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

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
timernumberYesID of the timer.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
}
let triggerTime = new Date().getTime();
triggerTime += 3000;

try {
  systemTimer.createTimer(options).then((timerId: number) => {
    systemTimer.startTimer(timerId, triggerTime);
    systemTimer.stopTimer(timerId);
    systemTimer.destroyTimer(timerId, (error: BusinessError) => {
      if (error) {
        console.info(`Failed to destroy the timer. Message: ${error.message}, code: ${error.code}`);
        return;
      }
    console.info(`Succeeded in destroying the timer.`);
    });
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

systemTimer.destroyTimer

destroyTimer(timer: number): Promise<void>

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

System capability: SystemCapability.MiscServices.Time

Parameters

NameTypeMandatoryDescription
timernumberYesID of the timer.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Time and Time Zone Service Error Codes.

IDError Message
202Permission verification failed. A non-system application calls a system API.
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let options: systemTimer.TimerOptions = {
  type: systemTimer.TIMER_TYPE_REALTIME,
  repeat:false
}
let triggerTime = new Date().getTime();
triggerTime += 3000;

try {
  systemTimer.createTimer(options).then((timerId: number) => {
    systemTimer.startTimer(timerId, triggerTime);
    systemTimer.stopTimer(timerId);
    systemTimer.destroyTimer(timerId).then(() => {
      console.info(`Succeeded in destroying the timer.`);
    }).catch((error: BusinessError) => {
      console.info(`Failed to destroy the timer. Message: ${error.message}, code: ${error.code}`);
    });
    console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
  }).catch((error: BusinessError) => {
    console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
  });
} catch(e) {
  let error = e as BusinessError;
  console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`);
}

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Basic Services Kit

harmony 鸿蒙DeviceInfo

harmony 鸿蒙InitSync

harmony 鸿蒙OH_Print

harmony 鸿蒙OsAccount

harmony 鸿蒙Pasteboard

harmony 鸿蒙Print_Margin

harmony 鸿蒙Print_PageSize

harmony 鸿蒙Print_PrintAttributes

harmony 鸿蒙Print_PrintDocCallback

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/40T3y5