未验证 提交 2e49e8f3 编写于 作者: O openharmony_ci 提交者: Gitee

!15637 翻译完成:14743+15098+14761+14524+15298+15329 任务调度相关文档

Merge pull request !15637 from wusongqing/TR14743
......@@ -16,6 +16,14 @@ When developing an application, you can override the APIs of this module and add
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
```
## Attributes
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) | Yes| No| Context of the **WorkSchedulerExtension**. This context is inherited from **ExtensionContext**.|
## WorkSchedulerExtensionAbility.onWorkStart
onWorkStart(work: workScheduler.WorkInfo): void
......
# WorkSchedulerExtensionContext
The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility.
This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. 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.
## Usage
The context is obtained through a WorkSchedulerExtensionAbility child class instance.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext.
}
}
```
......@@ -430,7 +430,7 @@ Provides detailed information about the task. For details about the constraints
| isPersisted | boolean | No | Whether to enable persistent storage for the task. |
| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. |
| idleWaitTime | number | No | Time to wait in the idle state. |
| parameters | {[key: string]: any} | No | Carried parameters. |
| parameters | {[key: string]: number | string | boolean} | No | Carried parameters. |
## NetworkType
Enumerates the network types that can trigger the task.
......
# Task Management
# Background Task Management
- Background Task
- [Background Task Management Overview](background-task-overview.md)
......@@ -8,6 +8,6 @@
- [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md)
- [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md)
- Agent-Powered Scheduled Reminder
- Agent-Powered Reminder
- [Agent-Powered Reminder Overview](reminder-agent-overview.md)
- [Agent-Powered Reminder Development](reminder-agent-development.md)
\ No newline at end of file
......@@ -41,7 +41,7 @@ Adhere to the following constraints and rules when using transient tasks:
- **When to cancel**: The application shall proactively cancel the request when the transient task is complete, rather than waiting for a system callback. Otherwise, the time frame allowed for the application to run in the background will be affected.
- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.)
- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). The default quota for a single day is 10 minutes, and the maximum quota for each request is 3 minutes. After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.)
## Continuous Tasks
Continuous tasks provide background running lifecycle support for services that can be directly perceived by users and need to run in the background. For example, if a service needs to play audio or continue with navigation and positioning in the background, which can be perceived by users, it can execute a continuous task in the respective background mode.
......@@ -58,7 +58,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas
| audioRecording | Audio input | A recording task is running. | - |
| location | Positioning and navigation | A positioning task is running. | - |
| bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - |
| multiDeviceConnection | Distributed interconnection | A distributed task is running. | - |
| multiDeviceConnection | Multi-device application collaboration | A distributed task is running. | - |
| wifiInteraction | WLAN transmission | A WLAN-related task is running.| System API, which is available only to system applications|
| voip | Voice and video calls over VoIP | A call-related task is running. | System API, which is available only to system applications|
| taskKeeping | Computing task | A computing task is running | Effective only for specific devices |
......
......@@ -38,10 +38,10 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-a
For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md).
1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission (ohos.permission.KEEP_BACKGROUND_RUNNING) and background mode type in the **module.json5** file.
1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **module.json5** file, and declare the corresponding background mode type for the ability that needs to use the task.
```
"module": {
```
"module": {
"abilities": [
{
"backgroundModes": [
......@@ -55,18 +55,18 @@ For details about the stage model, see [Stage Model Development Overview](../app
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
}
```
2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details, see [UIAbility Component Overview](../application-models/uiability-overview.md).
```ts
import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
```ts
import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
@Entry
@Component
struct Index {
@Entry
@Component
struct Index {
@State message: string = 'test'
// Use getContext to obtain the context of the Page ability.
private context: any = getContext(this)
......@@ -148,21 +148,21 @@ struct Index {
}
.height('100%')
}
}
```
}
```
3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Using Ability Call (Intra-Device)](../application-models/uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-ability-call).
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
const MSG_SEND_METHOD: string = 'CallSendMsg';
const MSG_SEND_METHOD: string = 'CallSendMsg';
let mContext = null;
let mContext = null;
function startContinuousTask() {
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
......@@ -196,9 +196,9 @@ function startContinuousTask() {
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
}
function stopContinuousTask() {
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
......@@ -208,9 +208,9 @@ function stopContinuousTask() {
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
}
class MySequenceable {
class MySequenceable {
num: number = 0;
str: String = "";
......@@ -230,9 +230,9 @@ class MySequenceable {
this.str = messageParcel.readString();
return true;
}
}
}
function sendMsgCallback(data) {
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new MySequenceable(0, "")
data.readSequenceable(receivedData)
......@@ -244,9 +244,9 @@ function sendMsgCallback(data) {
stopContinuousTask();
}
return new MySequenceable(10, "Callee test");
}
}
export default class BgTaskAbility extends UIAbility {
export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate")
this.callee.on("test", sendMsgCallback);
......@@ -284,21 +284,21 @@ export default class BgTaskAbility extends UIAbility {
onBackground() {
console.info("[Demo] BgTaskAbility onBackground")
}
};
```
};
```
### Development in the FA Model
For details about how to use the ServiceAbility in the FA model, see [ServiceAbility Component Overview](../application-models/serviceability-overview.md).
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the ServiceAbility. In the **onStart** callback of the ServiceAbility, call **startBackgroundRunning()** to declare that the ServiceAbility needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks.
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the ServiceAbility. After obtaining the proxy of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks.
1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**.
1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **config.json** file, and declare the corresponding background mode type for the ServiceAbility that needs to use the task.
```json
"module": {
```json
"module": {
"package": "com.example.myapplication",
"abilities": [
{
......@@ -306,7 +306,7 @@ If an application needs to interact with a continuous task in the background (fo
"dataTransfer",
"location"
], // Background mode
"type": "service" // The ability type is service.
"type": "service" // The ability type is Service.
}
],
"reqPermissions": [
......@@ -314,18 +314,18 @@ If an application needs to interact with a continuous task in the background (fo
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
}
```
2. Call the APIs for requesting and canceling a continuous task in the Service ability.
2. Call the APIs for requesting and canceling a continuous task in the ServiceAbility.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
function startContinuousTask() {
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
......@@ -359,9 +359,9 @@ function startContinuousTask() {
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
}
function stopContinuousTask() {
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
......@@ -371,18 +371,18 @@ function stopContinuousTask() {
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
}
async function processAsyncJobs() {
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
}
let mMyStub;
let mMyStub;
class MyStub extends rpc.RemoteObject {
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
......@@ -405,9 +405,9 @@ class MyStub extends rpc.RemoteObject {
}
return true;
}
}
}
export default {
export default {
onStart() {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
......@@ -431,5 +431,5 @@ export default {
onCommand(want, startId) {
console.info('ServiceAbility onCommand');
}
};
```
};
```
\ No newline at end of file
......@@ -6,6 +6,9 @@ To further balance power consumption overhead of the system, privileged system a
To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions.
## Constraints
Only system applications can request efficiency resources.
## Available APIs
**Table 1** Main APIs for efficiency resources
......@@ -22,11 +25,11 @@ To upgrade your application as a privileged application, you must evaluate your
2. When the task is complete, release the resources in time. You can choose whether to release some or all resources.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// Request efficiency resources.
let request = {
// Request efficiency resources.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT |
backgroundTaskManager.ResourceType.TIMER,
isApply: true,
......@@ -34,36 +37,36 @@ let request = {
reason: "apply",
isPersist: true,
isProcess: true,
};
};
let res;
try {
let res;
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
}
// Release some efficiency resources.
request = {
// Release some efficiency resources.
request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT,
isApply: false,
timeOut: 0,
reason: "reset",
isPersist: true,
isProcess: true,
};
try {
};
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
}
// Release all efficiency resources.
try {
// Release all efficiency resources.
try {
backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
} catch (error) {
console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
\ No newline at end of file
......@@ -2,7 +2,8 @@
## When to Use
If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks.
For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
## Available APIs
......@@ -38,7 +39,7 @@ storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-work
isRepeat| boolean |Whether the task is repeated.
repeatCycleTime| number |Repeat interval.
repeatCount | number|Number of repeat times.
parameters | {[key: string]: any} |Carried parameters.
parameters | {[key: string]: number | string | boolean} |Carried parameters.
**Table 3** Work Scheduler callbacks
......@@ -64,26 +65,26 @@ onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops.
2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md).
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
export default class MyExtension extends WorkSchedulerExtensionAbility {
export default class MyExtension extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
}
onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
}
}
```
}
```
3. Start a Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
let workInfo = {
let workInfo = {
workId: 1,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
......@@ -96,22 +97,22 @@ let workInfo = {
mykey2: true,
mykey3: 1.5
}
}
try{
}
try{
workScheduler.startWork(workInfo);
console.info('workschedulerLog startWork success');
} catch (error) {
} catch (error) {
console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
4. Stop the Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
let workInfo = {
let workInfo = {
workId: 1,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
......@@ -124,20 +125,21 @@ let workInfo = {
mykey2: true,
mykey3: 1.5
}
}
try{
}
try{
workScheduler.stopWork(workInfo, false);
console.info('workschedulerLog stopWork success');
} catch (error) {
} catch (error) {
console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
5. Obtain a specified Work Scheduler task.
```ts
try{
```ts
try{
workScheduler.getWorkStatus(50, (error, res) => {
if (error) {
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
......@@ -147,16 +149,15 @@ try{
}
}
});
} catch (error) {
} catch (error) {
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
6. Obtain all the Work Scheduler tasks.
```ts
try{
```ts
try{
workScheduler.obtainAllWorks((error, res) =>{
if (error) {
console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
......@@ -164,26 +165,26 @@ try{
console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
}
});
} catch (error) {
} catch (error) {
console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
7. Stop and clear all the Work Scheduler tasks.
```ts
try{
```ts
try{
workScheduler.stopAndClearWorks();
console.info(`workschedulerLog stopAndClearWorks success`);
} catch (error) {
} catch (error) {
console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
8. Check whether the last execution of a specified Work Scheduler task has timed out.
```ts
try{
```ts
try{
workScheduler.isLastWorkTimeOut(500, (error, res) =>{
if (error) {
onsole.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
......@@ -191,8 +192,7 @@ try{
console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
}
});
} catch (error) {
} catch (error) {
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
}
```
}
```
# Resource Scheduler Subsystem Changelog
## cl.resourceschedule.workScheduler
The data type of the **parameters** attribute value is changed. Specifically, the number, string, and boolean types are supported, but the any type is not.
**Change Impact**
For applications developed based on OpenHarmony3.2.10.7 and later SDK versions, the **parameters** attribute value can use the number, string, and boolean types only. If it uses the any type, a compilation error is reported.
**Key API/Component Changes**
The **parameters** attribute in @ohos.resourceschedule.workScheduler.d.ts is changed.
| Class| API Type| Statement Before the Change| Statement After the Change|
| -- | -- | -- | -- |
| workScheduler.WorkInfo | field | parameters?: {[key: string]: any} | parameters?: {[key: string]: number | string | boolean} |
**Adaptation Guide**
The **parameters** attribute uses the {[key: string]: number | string | boolean} data type.
# Resource Scheduler Subsystem Changelog
## cl.resourceschedule.workScheduler
The WorkSchedulerExtensionAbility provides a default WorkSchedulerExtensionContext.
**Change Impact**
Applications developed based on OpenHarmony4.0.5.1 and later SDK versions can use the default context attribute as the context environment of a WorkSchedulerExtension.
**Key API/Component Changes**
The context attribute is added to **@ohos.WorkSchedulerExtensionAbility.d.ts**. The **application/WorkSchedulerExtensionContext.d.ts** file is added, which is inherited from ExtensionContext.
| Module| Class| Method/Attribute/Enum/Constant| Change Type|
| -- | -- | -- | -- |
| @ohos.WorkSchedulerExtensionAbility.d.ts | WorkSchedulerExtensionAbility | context: WorkSchedulerExtensionContext; | Added|
| application/WorkSchedulerExtensionContext.d.ts | WorkSchedulerExtensionContext | - | Added|
**Adaptation Guide**
The context is obtained through a WorkSchedulerExtensionAbility child class instance.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext.
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册