harmony(鸿蒙)Work Scheduler

2022-08-09 浏览 (767)

Work Scheduler

The workScheduler module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints.

The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.

NOTE

  • The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
  • The APIs of this module can be used only in the stage model.
  • For details about the constraints on the Work Scheduler usage, see Work Scheduler Overview.

Modules to Import

import workScheduler from '@ohos.workScheduler';

workScheduler.startWork

startWork(work: WorkInfo): boolean

Instructs the WorkSchedulerService to add the specified task to the execution queue.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workWorkInfoYesTask to be added to the execution queue.

Return value

TypeDescription
booleanReturns true if the task is added to the execution queue; returns false otherwise.

Example

  let workInfo = {
      workId: 1,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
      abilityName: "MyExtension",
      parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
  }
  var res = workScheduler.startWork(workInfo);
  console.info(`workschedulerLog res: ${res}`);

workScheduler.stopWork

stopWork(work: WorkInfo, needCancel?: boolean): boolean

Instructs the WorkSchedulerService to stop the specified task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workWorkInfoYesTask to stop.
needCancelbooleanYesWhether to cancel the task.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

  let workInfo = {
      workId: 1,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
      abilityName: "MyExtension",
      parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
     }
  var res = workScheduler.stopWork(workInfo, false);
  console.info(`workschedulerLog res: ${res}`);

workScheduler.getWorkStatus

getWorkStatus(workId: number, callback : AsyncCallback<WorkInfo>): void

Obtains the latest task status. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesTask ID.
callbackAsyncCallback<WorkInfo>YesCallback used to return the result. Returns the task status obtained from the WorkSchedulerService if the specified task ID is valid; returns null otherwise.

Example

  workScheduler.getWorkStatus(50, (err, res) => {
    if (err) {
      console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`);
    } else {
      for (let item in res) {
        console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
      }
    }
  });

workScheduler.getWorkStatus

getWorkStatus(workId: number): Promise<WorkInfo>

Obtains the latest task status. This API uses a promise to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesTask ID.

Return value

TypeDescription
Promise<WorkInfo>Promise used to return the result. Returns the task status obtained from the WorkSchedulerService if the specified task ID is valid; returns null otherwise.

Example

  workScheduler.getWorkStatus(50).then((res) => {
    for (let item in res) {
      console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
    }
  }).catch((err) => {
    console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`);
  })

workScheduler.obtainAllWorks

obtainAllWorks(callback : AsyncCallback<void>): Array<WorkInfo>

Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return all tasks associated with the current application.

Return value

TypeDescription
Array<WorkInfo>All tasks associated with the current application.

Example

  workScheduler.obtainAllWorks((err, res) =>{
    if (err) {
      console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`);
    } else {
      console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
    }
  });

workScheduler.obtainAllWorks

obtainAllWorks(): Promise<Array<WorkInfo>>

Obtains all tasks associated with this application. This API uses a promise to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Return value

TypeDescription
Promise<Array<WorkInfo>>Promise used to return all tasks associated with the current application.

Example

  workScheduler.obtainAllWorks().then((res) => {
    console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
  }).catch((err) => {
    console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`);
  })

workScheduler.stopAndClearWorks

stopAndClearWorks(): boolean

Stops and cancels all tasks associated with the current application.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Example

  let res = workScheduler.stopAndClearWorks();
  console.info(`workschedulerLog res: ${res}`);

workScheduler.isLastWorkTimeOut

isLastWorkTimeOut(workId: number, callback : AsyncCallback<void>): boolean

Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesTask ID.
callbackAsyncCallback<void>YesCallback used to return the result. Returns true if the last execution of the specified task timed out; returns false otherwise.

Return value

TypeDescription
booleanCallback used to return the result. Returns true if the last execution of the specified task timed out; returns false otherwise.

Example

  workScheduler.isLastWorkTimeOut(500, (err, res) =>{
    if (err) {
      console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`);
    } else {
      console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
    }
  });

workScheduler.isLastWorkTimeOut

isLastWorkTimeOut(workId: number): Promise<boolean>

Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesTask ID.

Return value

TypeDescription
Promise<boolean>Promise used to return the result. Returns true if the last execution of the specified task timed out; returns false otherwise.

Example

  workScheduler.isLastWorkTimeOut(500)
    .then(res => {
      console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
    })
    .catch(err =>  {
      console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`);
    });

WorkInfo

Provides detailed information about the task. For details about the constraints on configuring WorkInfo, see Work Scheduler Overview.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameTypeMandatoryDescription
workIdnumberYesTask ID.
bundleNamestringYesName of the Work Scheduler task bundle.
abilityNamestringYesName of the component to be notified by a Work Scheduler callback.
networkTypeNetworkTypeNoNetwork type.
isChargingbooleanNoWhether the device is charging.
chargerTypeChargingTypeNoCharging type.
batteryLevelnumberNoBattery level.
batteryStatusBatteryStatusNoBattery status.
storageRequestStorageRequestNoStorage status.
isRepeatbooleanNoWhether the task is repeated.
repeatCycleTimenumberNoRepeat interval.
repeatCountnumberNoNumber of repeat times.
isPersistedbooleanNoWhether to enable persistent storage for the task.
isDeepIdlebooleanNoWhether the device needs to enter the idle state.
idleWaitTimenumberNoTime to wait in the idle state.
parameters{[key: string]: any}NoCarried parameters.

NetworkType

Enumerates the network types that can trigger the task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameDefault ValueDescription
NETWORK_TYPE_ANY0Any network type.
NETWORK_TYPE_MOBILE1Mobile network.
NETWORK_TYPE_WIFI2Wi-Fi network.
NETWORK_TYPE_BLUETOOTH3Bluetooth network.
NETWORK_TYPE_WIFI_P2P4Wi-Fi P2P network.
NETWORK_TYPE_ETHERNET5Ethernet.

ChargingType

Enumerates the charging types that can trigger the task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameDefault ValueDescription
CHARGING_PLUGGED_ANY0Any charging type.
CHARGING_PLUGGED_AC1DC charging.
CHARGING_PLUGGED_USB2USB charging.
CHARGING_PLUGGED_WIRELESS3Wireless charging.

BatteryStatus

Enumerates the battery states that can trigger the task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameDefault ValueDescription
BATTERY_STATUS_LOW0A low battery alert is displayed.
BATTERY_STATUS_OKAY1The battery level is restored from low to normal.
BATTERY_STATUS_LOW_OR_OKAY2The battery level is restored from low to normal, or a low battery alert is displayed.

StorageRequest

Enumerates the storage states that can trigger the task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameDefault ValueDescription
STORAGE_LEVEL_LOW0The storage space is insufficient.
STORAGE_LEVEL_OKAY1The storage space is restored from insufficient to normal.
STORAGE_LEVEL_LOW_OR_OKAY2The storage space is restored from insufficient to normal, or the storage space is insufficient.

你可能感兴趣的鸿蒙文章

harmony(鸿蒙)APIs

harmony(鸿蒙)API Reference Document Description

harmony(鸿蒙)BundleStatusCallback

harmony(鸿蒙)innerBundleManager(deprecated)

harmony(鸿蒙)distributedBundle

harmony(鸿蒙)Bundle

harmony(鸿蒙)Context

harmony(鸿蒙)DataUriUtils

harmony(鸿蒙)EnterpriseAdminExtensionAbility

harmony(鸿蒙)Work Scheduler Callbacks

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