我看文档中可以用@ohos.systemTimer 来实现定时器,将repeat设置为true,怎么才能开启循环任务,测试只能执行一次

import systemTimer from '@ohos.systemTimer';
import Logger from '@ohos/ohmodule/src/main/ets/common/core/Logger';
import Properties from '@ohos/ohmodule/src/main/ets/common/core/Properties';

export class ScheduledTask {
  properties: Properties
  logger: Logger


  constructor(properties: Properties) {
    this.properties = properties
    this.logger = new Logger(properties)
  }

  create(): Promise<number> {
    return new Promise((resolve, reject) => {
      let options = {
        type: systemTimer.TIMER_TYPE_EXACT,
        repeat: true,
        interval: 60 * 1000
      }
      systemTimer.createTimer(options).then((timerId: number) => {
        resolve(timerId)
      }).catch((err: Error) => {
        err.message = `createTimer error: ${err.message}`
        this.logger.error(err)
        reject(err)
      })
    })
  }

  start(timerId): Promise<boolean> {
    return new Promise((resolve, reject) => {
      systemTimer.startTimer(timerId,new Date().getTime()).then(() => {
        resolve(true)
      }).catch((err: Error) => {
        err.message = `startTimer error: ${err.message}`
        this.logger.error(err)
        reject(err)
      })
    })
  }

  execute(callback: () => void) {
    this.create().then(timerId => {
      this.start(timerId).then(() => {
        callback()
      })
    })
  }
}

 

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐