openharmony 鸿蒙 js-apis-resourceschedule-workScheduler

2025-06-12 浏览 (2)

@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)

The workScheduler module provides the APIs for registering, canceling, and querying deferred tasks. You can use the APIs to register tasks that do not have high requirements on real-time performance as deferred tasks. The system schedules and executes the deferred tasks at an appropriate time, subject to the storage space, power consumption, 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.

Modules to Import

import { workScheduler } from '@kit.BackgroundTasksKit';

workScheduler.startWork

startWork(work: WorkInfo): void

Starts a deferred task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workWorkInfoYesDeferred task to start.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.
9700005Calling startWork failed.

Example

  import { BusinessError } from '@kit.BasicServicesKit';
  
  let workInfo: workScheduler.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
      }
  }
  try{
    workScheduler.startWork(workInfo);
    console.info('workschedulerLog startWork success');
  } catch (error) {
    console.error(`workschedulerLog startwork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
  }

workScheduler.stopWork

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

Stops a deferred task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workWorkInfoYesDeferred task to stop.
needCancelbooleanNoWhether to clear the task while stopping it.
The value true means to clear the task while stopping it, and false means to stop the task only. The default value is false.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.

Example

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

  let workInfo: workScheduler.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
      }
     }
  try{
    workScheduler.stopWork(workInfo, false);
    console.info('workschedulerLog stopWork success');
  } catch (error) {
    console.error(`workschedulerLog stopWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
  }

workScheduler.getWorkStatus

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

Obtains the information a deferred task. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesID of the deferred task.
callbackAsyncCallback<WorkInfo>YesCallback used to return the result. If workId is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.

Example

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

  workScheduler.getWorkStatus(50, (error: BusinessError, res: workScheduler.WorkInfo) => {
    if (error) {
      console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
    } else {
      console.info(`workschedulerLog getWorkStatus success, ${JSON.stringify(res)}`);
    }
  });

workScheduler.getWorkStatus

getWorkStatus(workId: number): Promise<WorkInfo>

Obtains the information a deferred task. This API uses a promise to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesID of the deferred task.

Return value

TypeDescription
Promise<WorkInfo>Promise used to return the result. If workId is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.

Example

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

  workScheduler.getWorkStatus(50).then((res: workScheduler.WorkInfo) => {
    console.info(`workschedulerLog getWorkStatus success, ${JSON.stringify(res)}`);
  }).catch((error: BusinessError) => {
    console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
  })

workScheduler.obtainAllWorksdeprecated

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

This API is deprecated since API version 10. You are advised to use workScheduler.obtainAllWorks10+ instead.

Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result. If all the deferred tasks are obtained, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.

workScheduler.obtainAllWorks10+

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

Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<Array<WorkInfo>>YesCallback used to return the result. If all the deferred tasks are obtained, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.

Example

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

  workScheduler.obtainAllWorks((error: BusinessError, res: Array<workScheduler.WorkInfo>) =>{
    if (error) {
      console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
    } else {
      console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
    }
  });

workScheduler.obtainAllWorks

obtainAllWorks(): Promise<Array<WorkInfo>>

Obtains all the deferred tasks. 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 the deferred tasks.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.

Example

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

  workScheduler.obtainAllWorks().then((res: Array<workScheduler.WorkInfo>) => {
    console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
  }).catch((error: BusinessError) => {
    console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
  })

workScheduler.stopAndClearWorks

stopAndClearWorks(): void

Stops and clears all the deferred tasks.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.

Example

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

  try{
    workScheduler.stopAndClearWorks();
    console.info(`workschedulerLog stopAndClearWorks success`);
  } catch (error) {
    console.error(`workschedulerLog stopAndClearWorks failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
  }

workScheduler.isLastWorkTimeOutdeprecated

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

This API is deprecated since API version 10. You are advised to use workScheduler.isLastWorkTimeOut10+ instead.

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

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesID of the deferred task.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.

workScheduler.isLastWorkTimeOut10+

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

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

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesID of the deferred task.
callbackAsyncCallback<boolean>YesCallback used to return the result.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.

Example

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

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

workScheduler.isLastWorkTimeOut

isLastWorkTimeOut(workId: number): Promise<boolean>

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

System capability: SystemCapability.ResourceSchedule.WorkScheduler

Parameters

NameTypeMandatoryDescription
workIdnumberYesID of the deferred task.

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true means that the last execution of the specified task times out, and false means the opposite.

Error codes

For details about the error codes, see Universal Error Codes and workScheduler Error Codes.

IDError Message
401Parameter error. Possible causes: Parameter verification failed.
9700001Memory operation failed.
9700002Parcel operation failed.
9700003System service operation failed.
9700004Check on workInfo failed.

Example

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

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

WorkInfo

Defines the information about the deferred task.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameTypeMandatoryDescription
workIdnumberYesID of the deferred task.
bundleNamestringYesBundle name of the application where the deferred task is located.
abilityNamestringYesAbility name in the bundle.
networkTypeNetworkTypeNoNetwork type.
isChargingbooleanNoWhether the device needs to enter the charging state to trigger deferred task scheduling.
- true: The device needs to enter the charging state to trigger deferred task scheduling.
- false: The device does not need to enter the charging state to trigger deferred task scheduling.
chargerTypeChargingTypeNoCharging type.
batteryLevelnumberNoBattery level.
batteryStatusBatteryStatusNoBattery status.
storageRequestStorageRequestNoStorage status.
isRepeatbooleanNoWhether the task is repeated.
- true: The task is repeated.
- false: The task is not repeated.
repeatCycleTimenumberNoRepeat interval, in milliseconds.
repeatCountnumberNoNumber of repeat times.
isPersistedbooleanNoWhether the registered deferred task can be saved in the system.
- true: The task can be saved. That is, the task can be restored after the system restarts.
- false: The task cannot be saved.
isDeepIdlebooleanNoWhether the device needs to enter the idle state to trigger deferred task scheduling.
- true: The device needs to enter the idle state to trigger deferred task scheduling.
- false: The device does not need to enter the idle state to trigger deferred task scheduling.
idleWaitTimenumberNoTime to wait in the idle state before triggering deferred task scheduling, in milliseconds.
parametersRecord<string, number |string |boolean>NoCarried parameters.

NetworkType

Enumerates the network types that can trigger deferred task scheduling.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameValueDescription
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 deferred task scheduling.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameValueDescription
CHARGING_PLUGGED_ANY0Any charging type.
CHARGING_PLUGGED_AC1DC charging.
CHARGING_PLUGGED_USB2USB charging.
CHARGING_PLUGGED_WIRELESS3Wireless charging.

BatteryStatus

Enumerates the battery statuses that can trigger deferred task scheduling.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameValueDescription
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 statuses that can trigger deferred task scheduling.

System capability: SystemCapability.ResourceSchedule.WorkScheduler

NameValueDescription
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 insufficient, or the storage space is restored from insufficient to normal.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Background Tasks Kit

harmony 鸿蒙BackgroundProcessManager

harmony 鸿蒙TransientTask

harmony 鸿蒙TransientTask_DelaySuspendInfo

harmony 鸿蒙background_process_manager.h

harmony 鸿蒙DeviceUsageStatistics Error Codes

harmony 鸿蒙backgroundTaskManager Error Codes

harmony 鸿蒙reminderAgentManager Error Codes

harmony 鸿蒙workScheduler Error Codes

harmony 鸿蒙@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)

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