提交 49e95ad9 编写于 作者: G Gloria

Update docs against 18363+18380+18295+18835+18855+18838

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 182ee8be
...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an ...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters** **Parameters**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
|AsyncCallback&lt;boolean&gt; |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| |AsyncCallback&lt;boolean&gt; |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.|
**Error codes** **Error codes**
...@@ -59,9 +59,9 @@ Checks whether this application is undergoing a stability test. This API uses a ...@@ -59,9 +59,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.|
**Error codes** **Error codes**
...@@ -94,9 +94,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -94,9 +94,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.|
**Error codes** **Error codes**
...@@ -128,9 +128,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -128,9 +128,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters** **Parameters**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| AsyncCallback&lt;boolean&gt; |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| | AsyncCallback&lt;boolean&gt; |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.|
**Error codes** **Error codes**
...@@ -164,9 +164,9 @@ Obtains the memory size of this application. This API uses a promise to return t ...@@ -164,9 +164,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| | Promise&lt;number&gt; | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.|
**Error codes** **Error codes**
...@@ -198,9 +198,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -198,9 +198,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters** **Parameters**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
|AsyncCallback&lt;number&gt; |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| |AsyncCallback&lt;number&gt; |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.|
**Error codes** **Error codes**
...@@ -298,6 +298,82 @@ appManager.getRunningProcessInformation((err, data) => { ...@@ -298,6 +298,82 @@ appManager.getRunningProcessInformation((err, data) => {
}); });
``` ```
## appManager.isSharedBundleRunning
isSharedBundleRunning(bundleName: string, versionCode: number): Promise\<boolean>;
Checks whether the shared library is in use. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| bundleName | string | Yes | Bundle name of the shared library.|
| versionCode | number | Yes | Version number of the shared library. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<boolean> | Promise used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.|
**Example**
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.isSharedBundleRunning(bundleName, versionCode).then((data) => {
console.log('The shared bundle running is: ${JSON.stringify(data)}');
}).catch((error) => {
console.error('error: ${JSON.stringify(error)}');
});
```
## appManager.isSharedBundleRunning
isSharedBundleRunning(bundleName: string, versionCode: number, callback: AsyncCallback\<boolean>): void;
Checks whether the shared library is in use. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| bundleName | string | Yes | Bundle name of the shared library.|
| versionCode | number | Yes | Version number of the shared library. |
**Return value**
| Type| Description|
| -------- | -------- |
|AsyncCallback\<boolean>> | Callback used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.|
**Example**
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.isSharedBundleRunning(bundleName, versionCode, (err, data) => {
if (err) {
console.error('err: ${JSON.stringify(err)}');
} else {
console.log('The shared bundle running is: ${JSON.stringify(data)}');
}
});
```
## appManager.on ## appManager.on
on(type: 'applicationState', observer: ApplicationStateObserver): number; on(type: 'applicationState', observer: ApplicationStateObserver): number;
...@@ -641,7 +717,7 @@ Obtains applications that are running in the foreground. This API uses a promise ...@@ -641,7 +717,7 @@ Obtains applications that are running in the foreground. This API uses a promise
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise used to return an array holding the application state data. | | Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise used to return an array holding the application state data.|
**Error codes** **Error codes**
...@@ -731,11 +807,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal ...@@ -731,11 +807,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.| | bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| | callback | AsyncCallback\<void\> | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.|
**Error codes** **Error codes**
......
...@@ -77,7 +77,6 @@ let media = mediaLibrary.getMediaLibrary(); ...@@ -77,7 +77,6 @@ let media = mediaLibrary.getMediaLibrary();
### getFileAssets<sup>7+</sup> ### getFileAssets<sup>7+</sup>
getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void
Obtains file assets (also called files). This API uses an asynchronous callback to return the result. Obtains file assets (also called files). This API uses an asynchronous callback to return the result.
...@@ -105,7 +104,7 @@ async function example() { ...@@ -105,7 +104,7 @@ async function example() {
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };
// Obtain the files in asynchronous callback mode. // Obtain the files in asynchronous callback mode.
media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { media.getFileAssets(imagesFetchOp, async (error, fetchFileResult) => {
// Check whether the result set of the obtained files is undefined. If yes, the API call fails. // Check whether the result set of the obtained files is undefined. If yes, the API call fails.
if (fetchFileResult == undefined) { if (fetchFileResult == undefined) {
console.error('get fetchFileResult failed with error: ' + error); console.error('get fetchFileResult failed with error: ' + error);
...@@ -124,8 +123,8 @@ async function example() { ...@@ -124,8 +123,8 @@ async function example() {
return; return;
} }
console.info('Get fetchFileResult successfully, count: ' + count); console.info('Get fetchFileResult successfully, count: ' + count);
// Obtain the first file in the result set in asynchronous callback mode. // Obtain the first file in the result set in asynchronous callback mode. If there are a large number of files, use getAllObject instead.
fetchFileResult.getFirstObject((error, fileAsset) => { fetchFileResult.getFirstObject(async (error, fileAsset) => {
// Check whether the first file is undefined. If yes, the API call fails. // Check whether the first file is undefined. If yes, the API call fails.
if (fileAsset == undefined) { if (fileAsset == undefined) {
console.error('get first object failed with error: ' + error); console.error('get first object failed with error: ' + error);
...@@ -178,7 +177,7 @@ async function example() { ...@@ -178,7 +177,7 @@ async function example() {
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };
// Obtain the files in promise mode. // Obtain the files in promise mode.
media.getFileAssets(imagesFetchOp).then((fetchFileResult) => { media.getFileAssets(imagesFetchOp).then(async (fetchFileResult) => {
// Obtain the total number of files in the result set. // Obtain the total number of files in the result set.
const count = fetchFileResult.getCount(); const count = fetchFileResult.getCount();
// Check whether the number is less than 0. If yes, the API call fails. // Check whether the number is less than 0. If yes, the API call fails.
...@@ -192,8 +191,8 @@ async function example() { ...@@ -192,8 +191,8 @@ async function example() {
return; return;
} }
console.info('Get fetchFileResult successfully, count: ' + count); console.info('Get fetchFileResult successfully, count: ' + count);
// Obtain the first file in the result set in promise mode. // Obtain the first file in the result set in promise mode. If there are a large number of files, use getAllObject instead.
fetchFileResult.getFirstObject().then((fileAsset) => { fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
// Call getNextObject to obtain the next file until the last one. // Call getNextObject to obtain the next file until the last one.
for (let i = 1; i < count; i++) { for (let i = 1; i < count; i++) {
...@@ -514,17 +513,18 @@ Obtains the albums. This API uses an asynchronous callback to return the result. ...@@ -514,17 +513,18 @@ Obtains the albums. This API uses an asynchronous callback to return the result.
```js ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
selections: '', let AlbumNoArgsfetchOp = {
selectionArgs: [], selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
}; selectionArgs:['New Album 1'],
media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { };
if (albumList != undefined) { media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => {
console.info('getAlbums successfully: ' + JSON.stringify(albumList)); if (albumList != undefined) {
} else { console.info('getAlbums successfully: ' + JSON.stringify(albumList));
console.error('getAlbums failed with error: ' + error); } else {
} console.error('getAlbums failed with error: ' + error);
}) }
})
} }
``` ```
...@@ -554,15 +554,16 @@ Obtains the albums. This API uses a promise to return the result. ...@@ -554,15 +554,16 @@ Obtains the albums. This API uses a promise to return the result.
```js ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
selections: '', let AlbumNoArgsfetchOp = {
selectionArgs: [], selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
}; selectionArgs:['New Album 1'],
media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { };
console.info('getAlbums successfully: ' + JSON.stringify(albumList)); media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => {
}).catch((error) => { console.info('getAlbums successfully: ' + JSON.stringify(albumList));
console.error('getAlbums failed with error: ' + error); }).catch((error) => {
}); console.error('getAlbums failed with error: ' + error);
});
} }
``` ```
...@@ -2021,7 +2022,7 @@ async function example() { ...@@ -2021,7 +2022,7 @@ async function example() {
### getNextObject<sup>7+</sup> ### getNextObject<sup>7+</sup>
getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void
Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
...@@ -2049,7 +2050,8 @@ async function example() { ...@@ -2049,7 +2050,8 @@ async function example() {
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
let fileAsset = await fetchFileResult.getFirstObject(); let fileAsset = await fetchFileResult.getFirstObject();
if (!fileAsset.isAfterLast) { console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName);
if (!fetchFileResult.isAfterLast()) {
fetchFileResult.getNextObject((error, fileAsset) => { fetchFileResult.getNextObject((error, fileAsset) => {
if (error) { if (error) {
console.error('fetchFileResult getNextObject failed with error: ' + error); console.error('fetchFileResult getNextObject failed with error: ' + error);
...@@ -2065,7 +2067,7 @@ async function example() { ...@@ -2065,7 +2067,7 @@ async function example() {
### getNextObject<sup>7+</sup> ### getNextObject<sup>7+</sup>
getNextObject(): Promise&lt;FileAsset&gt; getNextObject(): Promise&lt;FileAsset&gt;
Obtains the next file asset in the result set. This API uses a promise to return the result. Obtains the next file asset in the result set. This API uses a promise to return the result.
> **NOTE** > **NOTE**
...@@ -2093,7 +2095,8 @@ async function example() { ...@@ -2093,7 +2095,8 @@ async function example() {
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
let fileAsset = await fetchFileResult.getFirstObject(); let fileAsset = await fetchFileResult.getFirstObject();
if (!fileAsset.isAfterLast) { console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName);
if (!fetchFileResult.isAfterLast()) {
fetchFileResult.getNextObject().then((fileAsset) => { fetchFileResult.getNextObject().then((fileAsset) => {
console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
fetchFileResult.close(); fetchFileResult.close();
...@@ -2369,20 +2372,21 @@ Commits the modification in the album attributes to the database. This API uses ...@@ -2369,20 +2372,21 @@ Commits the modification in the album attributes to the database. This API uses
```js ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
selections: '', let AlbumNoArgsfetchOp = {
selectionArgs: [], selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
}; selectionArgs:['New Album 1'],
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); };
const album = albumList[0]; const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
album.albumName = 'hello'; const album = albumList[0];
album.commitModify((error) => { album.albumName = 'hello';
if (error) { album.commitModify((error) => {
console.error('commitModify failed with error: ' + error); if (error) {
return; console.error('commitModify failed with error: ' + error);
} return;
console.info('commitModify successful.'); }
}) console.info('commitModify successful.');
})
} }
``` ```
...@@ -2406,18 +2410,60 @@ Commits the modification in the album attributes to the database. This API uses ...@@ -2406,18 +2410,60 @@ Commits the modification in the album attributes to the database. This API uses
```js ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
selections: '', let AlbumNoArgsfetchOp = {
selectionArgs: [], selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
}; selectionArgs:['New Album 1'],
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); };
const album = albumList[0]; const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
album.albumName = 'hello'; const album = albumList[0];
album.commitModify().then(() => { album.albumName = 'hello';
console.info('commitModify successfully'); album.commitModify().then(() => {
}).catch((error) => { console.info('commitModify successfully');
console.error('commitModify failed with error: ' + error); }).catch((error) => {
}); console.error('commitModify failed with error: ' + error);
});
}
```
### getFileAssets<sup>7+</sup>
getFileAssets(callback: AsyncCallback&lt;FetchFileResult&gt;): void
Obtains the file assets in this album. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Callback used to return the file assets.|
**Example**
```js
async function example() {
// To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
let AlbumNoArgsfetchOp = {
selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'],
};
// Obtain the albums that meet the retrieval options and return the album list.
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
// Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
album.getFileAssets((error, fetchFileResult) => {
if (error) {
console.error('album getFileAssets failed with error: ' + error);
return;
}
let count = fetchFileResult.getCount();
console.info('album getFileAssets successfully, count: ' + count);
fetchFileResult.close();
});
} }
``` ```
...@@ -2442,27 +2488,28 @@ Obtains the file assets in this album. This API uses an asynchronous callback to ...@@ -2442,27 +2488,28 @@ Obtains the file assets in this album. This API uses an asynchronous callback to
```js ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
selections: '', let AlbumNoArgsfetchOp = {
selectionArgs: [], selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
}; selectionArgs:['New Album 1'],
let fileNoArgsfetchOp = { };
selections: '', let fileNoArgsfetchOp = {
selectionArgs: [], selections: '',
selectionArgs: [],
}
// Obtain the albums that meet the retrieval options and return the album list.
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
// Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
if (error) {
console.error('album getFileAssets failed with error: ' + error);
return;
} }
// Obtain the albums that meet the retrieval options and return the album list. let count = fetchFileResult.getCount();
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); console.info('album getFileAssets successfully, count: ' + count);
const album = albumList[0]; fetchFileResult.close();
// Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. });
album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
if (error) {
console.error('album getFileAssets failed with error: ' + error);
return;
}
let count = fetchFileResult.getCount();
console.info('album getFileAssets successfully, count: ' + count);
fetchFileResult.close();
});
} }
``` ```
...@@ -2492,25 +2539,26 @@ Obtains the file assets in this album. This API uses a promise to return the res ...@@ -2492,25 +2539,26 @@ Obtains the file assets in this album. This API uses a promise to return the res
```js ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
selections: '', let AlbumNoArgsfetchOp = {
selectionArgs: [], selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
}; selectionArgs:['New Album 1'],
let fileNoArgsfetchOp = { };
selections: '', let fileNoArgsfetchOp = {
selectionArgs: [], selections: '',
}; selectionArgs: [],
// Obtain the albums that meet the retrieval options and return the album list. };
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); // Obtain the albums that meet the retrieval options and return the album list.
const album = albumList[0]; const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
// Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. const album = albumList[0];
album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
let count = fetchFileResult.getCount(); album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => {
console.info('album getFileAssets successfully, count: ' + count); let count = fetchFileResult.getCount();
fetchFileResult.close(); console.info('album getFileAssets successfully, count: ' + count);
}).catch((error) => { fetchFileResult.close();
console.error('album getFileAssets failed with error: ' + error); }).catch((error) => {
}); console.error('album getFileAssets failed with error: ' + error);
});
} }
``` ```
......
...@@ -20,9 +20,7 @@ import reminderAgent from'@ohos.reminderAgent'; ...@@ -20,9 +20,7 @@ import reminderAgent from'@ohos.reminderAgent';
## reminderAgent.publishReminder<sup>(deprecated)</sup> ## reminderAgent.publishReminder<sup>(deprecated)</sup>
```ts
publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<number>): void publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<number>): void
```
Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
...@@ -39,7 +37,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ...@@ -39,7 +37,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
| callback | AsyncCallback\<number\> | Yes| Callback used to return the published reminder's ID.| | callback | AsyncCallback\<number> | Yes| Callback used to return the published reminder's ID.|
**Example** **Example**
```ts ```ts
...@@ -56,9 +54,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ...@@ -56,9 +54,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c
## reminderAgent.publishReminder<sup>(deprecated)</sup> ## reminderAgent.publishReminder<sup>(deprecated)</sup>
```ts
publishReminder(reminderReq: ReminderRequest): Promise\<number> publishReminder(reminderReq: ReminderRequest): Promise\<number>
```
Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
...@@ -78,7 +74,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ...@@ -78,7 +74,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<number\> | Promise used to return the published reminder's ID.| | Promise\<number> | Promise used to return the published reminder's ID.|
**Example** **Example**
```ts ```ts
...@@ -95,9 +91,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ...@@ -95,9 +91,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu
## reminderAgent.cancelReminder<sup>(deprecated)</sup> ## reminderAgent.cancelReminder<sup>(deprecated)</sup>
```ts
cancelReminder(reminderId: number, callback: AsyncCallback\<void>): void cancelReminder(reminderId: number, callback: AsyncCallback\<void>): void
```
Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result.
...@@ -112,7 +106,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba ...@@ -112,7 +106,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).| | reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -125,9 +119,7 @@ reminderAgent.cancelReminder(1, (err, data) => { ...@@ -125,9 +119,7 @@ reminderAgent.cancelReminder(1, (err, data) => {
## reminderAgent.cancelReminder<sup>(deprecated)</sup> ## reminderAgent.cancelReminder<sup>(deprecated)</sup>
```ts
cancelReminder(reminderId: number): Promise\<void> cancelReminder(reminderId: number): Promise\<void>
```
Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result.
...@@ -147,7 +139,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th ...@@ -147,7 +139,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
...@@ -159,9 +151,7 @@ reminderAgent.cancelReminder(1).then(() => { ...@@ -159,9 +151,7 @@ reminderAgent.cancelReminder(1).then(() => {
## reminderAgent.getValidReminders<sup>(deprecated)</sup> ## reminderAgent.getValidReminders<sup>(deprecated)</sup>
```ts
getValidReminders(callback: AsyncCallback\<Array\<ReminderRequest>>): void getValidReminders(callback: AsyncCallback\<Array\<ReminderRequest>>): void
```
Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders.
...@@ -175,7 +165,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th ...@@ -175,7 +165,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<[ReminderRequest](#reminderrequest)\>\> | Yes| Callback used to return an array of all valid reminders set by the current application.| | callback | AsyncCallback\<Array\<[ReminderRequest](#reminderrequest)>> | Yes| Callback used to return an array of all valid reminders set by the current application.|
**Example** **Example**
...@@ -209,9 +199,7 @@ reminderAgent.getValidReminders((err, reminders) => { ...@@ -209,9 +199,7 @@ reminderAgent.getValidReminders((err, reminders) => {
## reminderAgent.getValidReminders<sup>(deprecated)</sup> ## reminderAgent.getValidReminders<sup>(deprecated)</sup>
```ts
getValidReminders(): Promise\<Array\<ReminderRequest>> getValidReminders(): Promise\<Array\<ReminderRequest>>
```
Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders.
...@@ -225,7 +213,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th ...@@ -225,7 +213,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<Array\<[ReminderRequest](#reminderrequest)\>\> | Promise used to return an array of all valid reminders set by the current application.| | Promise\<Array\<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.|
**Example** **Example**
...@@ -259,9 +247,7 @@ reminderAgent.getValidReminders().then((reminders) => { ...@@ -259,9 +247,7 @@ reminderAgent.getValidReminders().then((reminders) => {
## reminderAgent.cancelAllReminders<sup>(deprecated)</sup> ## reminderAgent.cancelAllReminders<sup>(deprecated)</sup>
```ts
cancelAllReminders(callback: AsyncCallback\<void>): void cancelAllReminders(callback: AsyncCallback\<void>): void
```
Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result.
...@@ -275,7 +261,7 @@ Cancels all reminders set by the current application. This API uses an asynchron ...@@ -275,7 +261,7 @@ Cancels all reminders set by the current application. This API uses an asynchron
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -288,9 +274,7 @@ reminderAgent.cancelAllReminders((err, data) =>{ ...@@ -288,9 +274,7 @@ reminderAgent.cancelAllReminders((err, data) =>{
## reminderAgent.cancelAllReminders<sup>(deprecated)</sup> ## reminderAgent.cancelAllReminders<sup>(deprecated)</sup>
```ts
cancelAllReminders(): Promise\<void> cancelAllReminders(): Promise\<void>
```
Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. Cancels all reminders set by the current application. This API uses a promise to return the cancellation result.
...@@ -304,7 +288,7 @@ Cancels all reminders set by the current application. This API uses a promise to ...@@ -304,7 +288,7 @@ Cancels all reminders set by the current application. This API uses a promise to
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
...@@ -316,9 +300,7 @@ reminderAgent.cancelAllReminders().then(() => { ...@@ -316,9 +300,7 @@ reminderAgent.cancelAllReminders().then(() => {
## reminderAgent.addNotificationSlot<sup>(deprecated)</sup> ## reminderAgent.addNotificationSlot<sup>(deprecated)</sup>
```ts
addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\<void>): void addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\<void>): void
```
Adds a notification slot. This API uses an asynchronous callback to return the result. Adds a notification slot. This API uses an asynchronous callback to return the result.
...@@ -333,7 +315,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ...@@ -333,7 +315,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -351,9 +333,7 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ...@@ -351,9 +333,7 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => {
## reminderAgent.addNotificationSlot<sup>(deprecated)</sup> ## reminderAgent.addNotificationSlot<sup>(deprecated)</sup>
```ts
addNotificationSlot(slot: NotificationSlot): Promise\<void> addNotificationSlot(slot: NotificationSlot): Promise\<void>
```
Adds a notification slot. This API uses a promise to return the result. Adds a notification slot. This API uses a promise to return the result.
...@@ -373,7 +353,7 @@ Adds a notification slot. This API uses a promise to return the result. ...@@ -373,7 +353,7 @@ Adds a notification slot. This API uses a promise to return the result.
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
...@@ -391,9 +371,7 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ...@@ -391,9 +371,7 @@ reminderAgent.addNotificationSlot(mySlot).then(() => {
## reminderAgent.removeNotificationSlot<sup>(deprecated)</sup> ## reminderAgent.removeNotificationSlot<sup>(deprecated)</sup>
```ts
removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
```
Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result.
...@@ -408,7 +386,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c ...@@ -408,7 +386,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -423,9 +401,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ...@@ -423,9 +401,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION,
## reminderAgent.removeNotificationSlot<sup>(deprecated)</sup> ## reminderAgent.removeNotificationSlot<sup>(deprecated)</sup>
```ts
removeNotificationSlot(slotType: notification.SlotType): Promise<void> removeNotificationSlot(slotType: notification.SlotType): Promise<void>
```
Removes a notification slot of a specified type. This API uses a promise to return the result. Removes a notification slot of a specified type. This API uses a promise to return the result.
...@@ -445,7 +421,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu ...@@ -445,7 +421,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
...@@ -568,7 +544,6 @@ Defines the reminder to publish. ...@@ -568,7 +544,6 @@ Defines the reminder to publish.
## ReminderRequestCalendar<sup>(deprecated)</sup> ## ReminderRequestCalendar<sup>(deprecated)</sup>
ReminderRequestCalendar extends ReminderRequest
Defines a reminder for a calendar event. Defines a reminder for a calendar event.
...@@ -581,13 +556,12 @@ Defines a reminder for a calendar event. ...@@ -581,13 +556,12 @@ Defines a reminder for a calendar event.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.|
| repeatMonths | Array\<number\> | No| Month in which the reminder repeats.| | repeatMonths | Array\<number> | No| Month in which the reminder repeats.|
| repeatDays | Array\<number\> | No| Date on which the reminder repeats.| | repeatDays | Array\<number> | No| Date on which the reminder repeats.|
## ReminderRequestAlarm<sup>(deprecated)</sup> ## ReminderRequestAlarm<sup>(deprecated)</sup>
ReminderRequestAlarm extends ReminderRequest
Defines a reminder for an alarm. Defines a reminder for an alarm.
...@@ -601,13 +575,11 @@ Defines a reminder for an alarm. ...@@ -601,13 +575,11 @@ Defines a reminder for an alarm.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| hour | number | Yes| Hour portion of the reminder time.| | hour | number | Yes| Hour portion of the reminder time.|
| minute | number | Yes| Minute portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.|
| daysOfWeek | Array\<number\> | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| | daysOfWeek | Array\<number> | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.|
## ReminderRequestTimer<sup>(deprecated)</sup> ## ReminderRequestTimer<sup>(deprecated)</sup>
ReminderRequestTimer extends ReminderRequest
Defines a reminder for a scheduled timer. Defines a reminder for a scheduled timer.
> **NOTE** > **NOTE**
......
...@@ -170,7 +170,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th ...@@ -170,7 +170,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| PPromise\<void> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Error codes** **Error codes**
...@@ -611,7 +611,7 @@ Defines the reminder to publish. ...@@ -611,7 +611,7 @@ Defines the reminder to publish.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.|
| actionButton<sup>10+</sup> | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions. | | actionButton<sup>10+</sup> | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.|
| wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.|
| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.|
| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.|
......
# @ohos.taskpool (Using the Task Pool) # @ohos.taskpool (Starting the Task Pool)
The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance. The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance.
You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. (The task priority mechanism is not supported yet.) You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**.
If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. (The load balancing mechanism is not supported yet.) If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads.
The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
...@@ -32,13 +32,13 @@ Enumerates the priorities available for created tasks. ...@@ -32,13 +32,13 @@ Enumerates the priorities available for created tasks.
**Example** **Example**
```ts ```ts
function func(args) { @Concurrent
"use concurrent"; function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolPriority() {
let task = new taskpool.Task(func, 100); let task = new taskpool.Task(printArgs, 100);
let highCount = 0; let highCount = 0;
let mediumCount = 0; let mediumCount = 0;
...@@ -65,7 +65,7 @@ async function taskpoolTest() { ...@@ -65,7 +65,7 @@ async function taskpoolTest() {
}) })
} }
} }
taskpoolTest(); taskpoolPriority();
``` ```
## Task ## Task
...@@ -99,12 +99,12 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -99,12 +99,12 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts ```ts
@Concurrent @Concurrent
function func(args) { function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let task = new taskpool.Task(func, "this is my first Task"); let task = new taskpool.Task(printArgs, "this is my first Task");
``` ```
### Attributes ### Attributes
...@@ -151,17 +151,17 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -151,17 +151,17 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts ```ts
@Concurrent @Concurrent
function func(args) { function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolExecute() {
let value = await taskpool.execute(func, 100); let value = await taskpool.execute(printArgs, 100);
console.log("taskpool result: " + value); console.log("taskpool result: " + value);
} }
taskpoolTest(); taskpoolExecute();
``` ```
## taskpool.execute ## taskpool.execute
...@@ -199,18 +199,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -199,18 +199,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts ```ts
@Concurrent @Concurrent
function func(args) { function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolExecute() {
let task = new taskpool.Task(func, 100); let task = new taskpool.Task(printArgs, 100);
let value = await taskpool.execute(task); let value = await taskpool.execute(task);
console.log("taskpool result: " + value); console.log("taskpool result: " + value);
} }
taskpoolTest(); taskpoolExecute();
``` ```
## taskpool.cancel ## taskpool.cancel
...@@ -239,14 +239,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -239,14 +239,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example of successful task cancellation** **Example of successful task cancellation**
```ts ```ts
function func(args) { @Concurrent
"use concurrent"; function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolCancel() {
let task = new taskpool.Task(func, 100); let task = new taskpool.Task(printArgs, 100);
taskpool.execute(task); taskpool.execute(task);
try { try {
taskpool.cancel(task); taskpool.cancel(task);
...@@ -255,20 +255,20 @@ async function taskpoolTest() { ...@@ -255,20 +255,20 @@ async function taskpoolTest() {
} }
} }
taskpoolTest(); taskpoolCancel();
``` ```
**Example of a failure to cancel a task that has been executed** **Example of a failure to cancel a task that has been executed**
```ts ```ts
function func(args) { @Concurrent
"use concurrent"; function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolCancel() {
let task = new taskpool.Task(func, 100); let task = new taskpool.Task(printArgs, 100);
let value = taskpool.execute(task); let value = taskpool.execute(task);
let start = new Date().getTime(); let start = new Date().getTime();
while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed.
...@@ -282,25 +282,25 @@ async function taskpoolTest() { ...@@ -282,25 +282,25 @@ async function taskpoolTest() {
} }
} }
taskpoolTest(); taskpoolCancel();
``` ```
**Example of a failure to cancel an ongoing task** **Example of a failure to cancel an ongoing task**
```ts ```ts
function func(args) { @Concurrent
"use concurrent"; function printArgs(args) {
console.log("func: " + args); console.log("printArgs: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolCancel() {
let task1 = new taskpool.Task(func, 100); let task1 = new taskpool.Task(printArgs, 100);
let task2 = new taskpool.Task(func, 200); let task2 = new taskpool.Task(printArgs, 200);
let task3 = new taskpool.Task(func, 300); let task3 = new taskpool.Task(printArgs, 300);
let task4 = new taskpool.Task(func, 400); let task4 = new taskpool.Task(printArgs, 400);
let task5 = new taskpool.Task(func, 500); let task5 = new taskpool.Task(printArgs, 500);
let task6 = new taskpool.Task(func, 600); let task6 = new taskpool.Task(printArgs, 600);
let res1 = taskpool.execute(task1); let res1 = taskpool.execute(task1);
let res2 = taskpool.execute(task2); let res2 = taskpool.execute(task2);
...@@ -315,7 +315,7 @@ async function taskpoolTest() { ...@@ -315,7 +315,7 @@ async function taskpoolTest() {
} }
} }
taskpoolTest(); taskpoolCancel();
``` ```
## Additional Information ## Additional Information
...@@ -327,7 +327,7 @@ The following sequenceable data types are supported: All Primitive Type (excludi ...@@ -327,7 +327,7 @@ The following sequenceable data types are supported: All Primitive Type (excludi
- The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**. - The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**.
- A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables. - A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables.
- A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions. - A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions.
- The decorator **@Concurrent** can be used only in the .ets file. To create a task in the task pool in the .ts file, use the statement **use concurrent**. - The decorator **@Concurrent** can be used only in .ets files.
### Using the Task Pool in Simple Mode ### Using the Task Pool in Simple Mode
...@@ -336,23 +336,23 @@ The following sequenceable data types are supported: All Primitive Type (excludi ...@@ -336,23 +336,23 @@ The following sequenceable data types are supported: All Primitive Type (excludi
```ts ```ts
// Common functions are supported, and variables passed in by input parameters are also supported. // Common functions are supported, and variables passed in by input parameters are also supported.
@Concurrent @Concurrent
function func(args) { function printArgs(args) {
console.log("func: " + args); console.log("func: " + args);
return args; return args;
} }
async function taskpoolTest() { async function taskpoolExecute() {
// taskpool.execute(task) // taskpool.execute(task)
let task = new taskpool.Task(func, "create task, then execute"); let task = new taskpool.Task(printArgs, "create task, then execute");
let val1 = await taskpool.execute(task); let val1 = await taskpool.execute(task);
console.log("taskpool.execute(task) result: " + val1); console.log("taskpool.execute(task) result: " + val1);
// taskpool.execute(function) // taskpool.execute(function)
let val2 = await taskpool.execute(func, "execute task by func"); let val2 = await taskpool.execute(printArgs, "execute task by func");
console.log("taskpool.execute(function) result: " + val2); console.log("taskpool.execute(function) result: " + val2);
} }
taskpoolTest(); taskpoolExecute();
``` ```
**Example 2** **Example 2**
...@@ -367,24 +367,24 @@ export var c = 2000; ...@@ -367,24 +367,24 @@ export var c = 2000;
import { c } from "./b"; import { c } from "./b";
@Concurrent @Concurrent
function test(a) { function printArgs(a) {
console.log(a); console.log(a);
console.log(c); console.log(c);
return a; return a;
} }
async function taskpoolTest() { async function taskpoolExecute() {
// taskpool.execute(task) // taskpool.execute(task)
let task = new taskpool.Task(test, "create task, then execute"); let task = new taskpool.Task(printArgs, "create task, then execute");
let val1 = await taskpool.execute(task); let val1 = await taskpool.execute(task);
console.log("taskpool.execute(task) result: " + val1); console.log("taskpool.execute(task) result: " + val1);
// taskpool.execute(function) // taskpool.execute(function)
let val2 = await taskpool.execute(test, "execute task by func"); let val2 = await taskpool.execute(printArgs, "execute task by func");
console.log("taskpool.execute(function) result: " + val2); console.log("taskpool.execute(function) result: " + val2);
} }
taskpoolTest(); taskpoolExecute();
``` ```
**Example 3** **Example 3**
...@@ -392,57 +392,52 @@ taskpoolTest(); ...@@ -392,57 +392,52 @@ taskpoolTest();
```ts ```ts
// The async functions are supported. // The async functions are supported.
@Concurrent @Concurrent
async function task() { async function delayExcute() {
let ret = await Promise.all([ let ret = await Promise.all([
new Promise(resolve => setTimeout(resolve, 1000, "resolved")) new Promise(resolve => setTimeout(resolve, 1000, "resolved"))
]); ]);
return ret; return ret;
} }
async function taskpoolTest() { async function taskpoolExecute() {
taskpool.execute(task).then((result) => { taskpool.execute(delayExcute).then((result) => {
console.log("TaskPoolTest task result: " + result); console.log("TaskPoolTest task result: " + result);
}); });
} }
taskpoolTest(); taskpoolExecute();
``` ```
**Example 4** **Example 4**
```ts ```ts
// Use use concurrent to create a task in the task pool in the .ts file. // c.ets
// c.ts @Concurrent
function test1(n) { function strSort(inPutArr) {
"use concurrent" let newArr = inPutArr.sort();
return n; return newArr;
} }
export async function taskpoolTest1() { export async function func1() {
console.log("taskpoolTest1 start"); console.log("taskpoolTest start");
var task = new taskpool.Task(test1, 100); let strArray = ['c test string', 'b test string', 'a test string'];
var task = new taskpool.Task(strSort, strArray);
var result = await taskpool.execute(task); var result = await taskpool.execute(task);
console.log("taskpoolTest1 result:" + result); console.log("func1 result:" + result);
} }
async function test2() { export async function func2() {
"use concurrent"
var ret = await Promise.all([
new Promise(resolve => setTimeout(resolve, 1000, "resolved"))
]);
return ret;
}
export async function taskpoolTest2() {
console.log("taskpoolTest2 start"); console.log("taskpoolTest2 start");
taskpool.execute(test2).then((result) => { let strArray = ['c test string', 'b test string', 'a test string'];
console.log("TaskPoolTest2 result: " + result); taskpool.execute(strSort, strArray).then((result) => {
console.log("func2 result: " + result);
}); });
} }
``` ```
```ts ```ts
/ / a.ets (in the same directory as c.ts) / / a.ets (in the same directory as c.ets)
import { taskpoolTest1, taskpoolTest2 } from "./c"; import { taskpoolTest1, taskpoolTest2 } from "./c";
taskpoolTest1(); func1();
taskpoolTest2(); func2();
``` ```
...@@ -83,9 +83,9 @@ import worker from '@ohos.worker'; ...@@ -83,9 +83,9 @@ import worker from '@ohos.worker';
// Create a Worker instance. // Create a Worker instance.
// In the FA model, the workers directory is at the same level as the pages directory in the entry module. // In the FA model, the workers directory is at the same level as the pages directory in the entry module.
const workerFAModel01 = new worker.ThreadWorker("workers/worker.js", {name:"first worker in FA model"}); const workerFAModel01 = new worker.ThreadWorker("workers/worker.ts", {name:"first worker in FA model"});
// In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. // In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module.
const workerFAModel02 = new worker.ThreadWorker("../workers/worker.js"); const workerFAModel02 = new worker.ThreadWorker("../workers/worker.ts");
// In the stage model, the workers directory is at the same level as the pages directory in the entry module. // In the stage model, the workers directory is at the same level as the pages directory in the entry module.
const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"});
...@@ -872,13 +872,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -872,13 +872,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// let data = e.data; // let data = e.data;
console.log("receive data from worker.js"); console.log("receive data from worker.ts");
} }
``` ```
...@@ -920,13 +920,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -920,13 +920,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// let data = e.data; // let data = e.data;
console.log("receive data from worker.js"); console.log("receive data from worker.ts");
} }
``` ```
...@@ -936,7 +936,7 @@ import worker from '@ohos.worker'; ...@@ -936,7 +936,7 @@ import worker from '@ohos.worker';
const workerPort = worker.workerPort; const workerPort = worker.workerPort;
workerPort.onmessage = function(e){ workerPort.onmessage = function(e){
// let data = e.data; // let data = e.data;
workerPort.postMessage("receive data from main.js"); workerPort.postMessage("receive data from main thread");
} }
``` ```
...@@ -960,7 +960,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -960,7 +960,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
``` ```
...@@ -1002,7 +1002,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -1002,7 +1002,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
...@@ -1013,7 +1013,7 @@ workerInstance.postMessage("hello world"); ...@@ -1013,7 +1013,7 @@ workerInstance.postMessage("hello world");
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerPort = worker.workerPort; const workerPort = worker.workerPort;
workerPort.onmessage = function(e) { workerPort.onmessage = function(e) {
console.log("receive main.js message"); console.log("receive main thread message");
} }
``` ```
...@@ -1045,7 +1045,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ...@@ -1045,7 +1045,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
``` ```
...@@ -1055,7 +1055,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ...@@ -1055,7 +1055,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.workerPort; const parentPort = worker.workerPort;
parentPort.onmessageerror = function(e) { parentPort.onmessageerror = function(e) {
console.log("worker.js onmessageerror") console.log("worker.ts onmessageerror")
} }
``` ```
...@@ -1130,7 +1130,7 @@ Defines the event handler to be called when an exception occurs during worker ex ...@@ -1130,7 +1130,7 @@ Defines the event handler to be called when an exception occurs during worker ex
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts")
``` ```
...@@ -1140,7 +1140,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") ...@@ -1140,7 +1140,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts")
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerPort = worker.workerPort const workerPort = worker.workerPort
workerPort.onerror = function(e){ workerPort.onerror = function(e){
console.log("worker.js onerror") console.log("worker.ts onerror")
} }
``` ```
...@@ -1193,9 +1193,9 @@ import worker from '@ohos.worker'; ...@@ -1193,9 +1193,9 @@ import worker from '@ohos.worker';
// Create a Worker instance. // Create a Worker instance.
// In the FA model, the workers directory is at the same level as the pages directory. // In the FA model, the workers directory is at the same level as the pages directory.
const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker in FA model"}); const workerFAModel01 = new worker.Worker("workers/worker.ts", {name:"first worker in FA model"});
// In the FA model, the workers directory is at the same level as the parent directory of the pages directory. // In the FA model, the workers directory is at the same level as the parent directory of the pages directory.
const workerFAModel02 = new worker.Worker("../workers/worker.js"); const workerFAModel02 = new worker.Worker("../workers/worker.ts");
// In the stage model, the workers directory is at the same level as the pages directory. // In the stage model, the workers directory is at the same level as the pages directory.
const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"});
...@@ -1275,7 +1275,7 @@ Sends a message to the worker thread. The data type of the message must be seque ...@@ -1275,7 +1275,7 @@ Sends a message to the worker thread. The data type of the message must be seque
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
var buffer = new ArrayBuffer(8); var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]); workerInstance.postMessage(buffer, [buffer]);
...@@ -1302,7 +1302,7 @@ Sends a message to the worker thread. The data type of the message must be seque ...@@ -1302,7 +1302,7 @@ Sends a message to the worker thread. The data type of the message must be seque
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
...@@ -1332,7 +1332,7 @@ Adds an event listener for the worker thread. This API provides the same functio ...@@ -1332,7 +1332,7 @@ Adds an event listener for the worker thread. This API provides the same functio
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.on("alert", (e)=>{ workerInstance.on("alert", (e)=>{
console.log("alert listener callback"); console.log("alert listener callback");
}) })
...@@ -1360,7 +1360,7 @@ Adds an event listener for the worker thread and removes the event listener afte ...@@ -1360,7 +1360,7 @@ Adds an event listener for the worker thread and removes the event listener afte
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.once("alert", (e)=>{ workerInstance.once("alert", (e)=>{
console.log("alert listener callback"); console.log("alert listener callback");
}) })
...@@ -1388,7 +1388,7 @@ Removes an event listener for the worker thread. This API provides the same func ...@@ -1388,7 +1388,7 @@ Removes an event listener for the worker thread. This API provides the same func
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. // Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
workerInstance.off("alert"); workerInstance.off("alert");
``` ```
...@@ -1408,7 +1408,7 @@ Terminates the worker thread to stop it from receiving messages. ...@@ -1408,7 +1408,7 @@ Terminates the worker thread to stop it from receiving messages.
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.terminate(); workerInstance.terminate();
``` ```
...@@ -1433,7 +1433,7 @@ Defines the event handler to be called when the worker thread exits. The handler ...@@ -1433,7 +1433,7 @@ Defines the event handler to be called when the worker thread exits. The handler
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.onexit = function(e) { workerInstance.onexit = function(e) {
console.log("onexit"); console.log("onexit");
} }
...@@ -1467,7 +1467,7 @@ Defines the event handler to be called when an exception occurs during worker ex ...@@ -1467,7 +1467,7 @@ Defines the event handler to be called when an exception occurs during worker ex
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.onerror = function(e) { workerInstance.onerror = function(e) {
console.log("onerror"); console.log("onerror");
} }
...@@ -1489,12 +1489,12 @@ Defines the event handler to be called when the host thread receives a message s ...@@ -1489,12 +1489,12 @@ Defines the event handler to be called when the host thread receives a message s
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ---------------------- | | ------ | ------------------------------ | ---- | ---------------------- |
| event | [MessageEvent](#messageeventt) | Yes | Message received.| | event | [MessageEvent](#messageeventt)| Yes | Message received.|
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// e: MessageEvent. The usage is as follows: // e: MessageEvent. The usage is as follows:
// let data = e.data; // let data = e.data;
...@@ -1518,12 +1518,12 @@ Defines the event handler to be called when the worker thread receives a message ...@@ -1518,12 +1518,12 @@ Defines the event handler to be called when the worker thread receives a message
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ---------- | | ------ | ------------------------------ | ---- | ---------- |
| event | [MessageEvent](#messageeventt) | Yes | Error data.| | event | [MessageEvent](#messageeventt)| Yes | Error data.|
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.onmessageerror= function(e) { workerInstance.onmessageerror= function(e) {
console.log("onmessageerror"); console.log("onmessageerror");
} }
...@@ -1555,7 +1555,7 @@ Adds an event listener for the worker thread. This API provides the same functio ...@@ -1555,7 +1555,7 @@ Adds an event listener for the worker thread. This API provides the same functio
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.addEventListener("alert", (e)=>{ workerInstance.addEventListener("alert", (e)=>{
console.log("alert listener callback"); console.log("alert listener callback");
}) })
...@@ -1583,7 +1583,7 @@ Removes an event listener for the worker thread. This API provides the same func ...@@ -1583,7 +1583,7 @@ Removes an event listener for the worker thread. This API provides the same func
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.addEventListener("alert", (e)=>{ workerInstance.addEventListener("alert", (e)=>{
console.log("alert listener callback"); console.log("alert listener callback");
}) })
...@@ -1617,7 +1617,7 @@ Dispatches the event defined for the worker thread. ...@@ -1617,7 +1617,7 @@ Dispatches the event defined for the worker thread.
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
``` ```
...@@ -1625,7 +1625,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is n ...@@ -1625,7 +1625,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is n
The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
// Usage 1: // Usage 1:
workerInstance.on("alert_on", (e)=>{ workerInstance.on("alert_on", (e)=>{
...@@ -1677,7 +1677,7 @@ Removes all event listeners for the worker thread. ...@@ -1677,7 +1677,7 @@ Removes all event listeners for the worker thread.
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.addEventListener("alert", (e)=>{ workerInstance.addEventListener("alert", (e)=>{
console.log("alert listener callback"); console.log("alert listener callback");
}) })
...@@ -1732,17 +1732,17 @@ Sends a message to the host thread from the worker thread. ...@@ -1732,17 +1732,17 @@ Sends a message to the host thread from the worker thread.
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// let data = e.data; // let data = e.data;
console.log("receive data from worker.js"); console.log("receive data from worker.ts");
} }
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e){ parentPort.onmessage = function(e){
...@@ -1773,22 +1773,22 @@ Sends a message to the host thread from the worker thread. ...@@ -1773,22 +1773,22 @@ Sends a message to the host thread from the worker thread.
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// let data = e.data; // let data = e.data;
console.log("receive data from worker.js"); console.log("receive data from worker.ts");
} }
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e){ parentPort.onmessage = function(e){
// let data = e.data; // let data = e.data;
parentPort.postMessage("receive data from main.js"); parentPort.postMessage("receive data from main thread");
} }
``` ```
...@@ -1806,12 +1806,12 @@ Terminates the worker thread to stop it from receiving messages. ...@@ -1806,12 +1806,12 @@ Terminates the worker thread to stop it from receiving messages.
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e) { parentPort.onmessage = function(e) {
...@@ -1836,22 +1836,22 @@ Defines the event handler to be called when the worker thread receives a message ...@@ -1836,22 +1836,22 @@ Defines the event handler to be called when the worker thread receives a message
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------------ | | ------ | ------------------------------------------------------------ | ---- | ------------------------ |
| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. |
| ev | [MessageEvent](#messageeventt) | Yes | Message received.| | ev | [MessageEvent](#messageeventt) | Yes | Message received.|
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.postMessage("hello world"); workerInstance.postMessage("hello world");
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e) { parentPort.onmessage = function(e) {
console.log("receive main.js message"); console.log("receive main thread message");
} }
``` ```
...@@ -1872,21 +1872,21 @@ Defines the event handler to be called when the worker thread receives a message ...@@ -1872,21 +1872,21 @@ Defines the event handler to be called when the worker thread receives a message
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ---------- | | ------ | ------------------------------ | ---- | ---------- |
| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.|
| ev | [MessageEvent](#messageeventt) | Yes | Error data.| | ev | [MessageEvent](#messageeventt)| Yes | Error data.|
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessageerror = function(e) { parentPort.onmessageerror = function(e) {
console.log("worker.js onmessageerror") console.log("worker.ts onmessageerror")
} }
``` ```
...@@ -1940,7 +1940,7 @@ Implements event listening. ...@@ -1940,7 +1940,7 @@ Implements event listening.
**Example** **Example**
```js ```js
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Worker("workers/worker.ts");
workerInstance.addEventListener("alert", (e)=>{ workerInstance.addEventListener("alert", (e)=>{
console.log("alert listener callback"); console.log("alert listener callback");
}) })
...@@ -2010,16 +2010,16 @@ Defines the event handler to be called when an exception occurs during worker ex ...@@ -2010,16 +2010,16 @@ Defines the event handler to be called when an exception occurs during worker ex
**Example** **Example**
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js") const workerInstance = new worker.Worker("workers/worker.ts")
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort const parentPort = worker.parentPort
parentPort.onerror = function(e){ parentPort.onerror = function(e){
console.log("worker.js onerror") console.log("worker.ts onerror")
} }
``` ```
...@@ -2045,17 +2045,17 @@ Exception: When an object created through a custom class is passed, no serializa ...@@ -2045,17 +2045,17 @@ Exception: When an object created through a custom class is passed, no serializa
> An FA project of API version 9 is used as an example. > An FA project of API version 9 is used as an example.
```js ```js
// main.js // Main thread
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("workers/worker.js"); const workerInstance = new worker.ThreadWorker("workers/worker.ts");
workerInstance.postMessage("message from main to worker"); workerInstance.postMessage("message from main thread to worker");
workerInstance.onmessage = function(d) { workerInstance.onmessage = function(d) {
// When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method.
let data = d.data; let data = d.data;
} }
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerPort = worker.workerPort; const workerPort = worker.workerPort;
class MyModel { class MyModel {
...@@ -2065,7 +2065,7 @@ class MyModel { ...@@ -2065,7 +2065,7 @@ class MyModel {
} }
} }
workerPort.onmessage = function(d) { workerPort.onmessage = function(d) {
console.log("worker.js onmessage"); console.log("worker.ts onmessage");
let data = d.data; let data = d.data;
let func1 = function() { let func1 = function() {
console.log("post message is function"); console.log("post message is function");
...@@ -2083,10 +2083,10 @@ workerPort.onmessage = function(d) { ...@@ -2083,10 +2083,10 @@ workerPort.onmessage = function(d) {
workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. workerPort.postMessage(obj2); // No serialization error occurs when passing obj2.
} }
workerPort.onmessageerror = function(e) { workerPort.onmessageerror = function(e) {
console.log("worker.js onmessageerror"); console.log("worker.ts onmessageerror");
} }
workerPort.onerror = function(e) { workerPort.onerror = function(e) {
console.log("worker.js onerror"); console.log("worker.ts onerror");
} }
``` ```
...@@ -2111,15 +2111,10 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther ...@@ -2111,15 +2111,10 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther
### FA Model ### FA Model
```js ```js
// main.js (The following assumes that the workers directory and pages directory are at the same level.) // Main thread (The following assumes that the workers directory and pages directory are at the same level.)
import worker from '@ohos.worker'; import worker from '@ohos.worker';
// Create a Worker instance in the main thread. // Create a Worker instance in the main thread.
const workerInstance = new worker.ThreadWorker("workers/worker.ts"); const workerInstance = new worker.ThreadWorker("workers/worker.ts");
// Create either a .json or .ts file.
// const workerInstance = new worker.ThreadWorker("workers/worker.js");
// In versions earlier than API version 9, use the following to create a Worker instance in the main thread.
// const workerInstance = new worker.Worker("workers/worker.js");
// The main thread transfers information to the worker thread. // The main thread transfers information to the worker thread.
workerInstance.postMessage("123"); workerInstance.postMessage("123");
...@@ -2128,7 +2123,7 @@ workerInstance.postMessage("123"); ...@@ -2128,7 +2123,7 @@ workerInstance.postMessage("123");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// data carries the information sent by the worker thread. // data carries the information sent by the worker thread.
let data = e.data; let data = e.data;
console.log("main.js onmessage"); console.log("main thread onmessage");
// Terminate the Worker instance. // Terminate the Worker instance.
workerInstance.terminate(); workerInstance.terminate();
...@@ -2136,7 +2131,7 @@ workerInstance.onmessage = function(e) { ...@@ -2136,7 +2131,7 @@ workerInstance.onmessage = function(e) {
// Call onexit(). // Call onexit().
workerInstance.onexit = function() { workerInstance.onexit = function() {
console.log("main.js terminate"); console.log("main thread terminate");
} }
``` ```
```js ```js
...@@ -2146,9 +2141,6 @@ import worker from '@ohos.worker'; ...@@ -2146,9 +2141,6 @@ import worker from '@ohos.worker';
// Create an object in the worker thread for communicating with the main thread. // Create an object in the worker thread for communicating with the main thread.
const workerPort = worker.workerPort const workerPort = worker.workerPort
// In versions earlier than API version 9, use the following to create an object in the worker thread for communicating with the main thread.
// const parentPort = worker.parentPort
// The worker thread receives information from the main thread. // The worker thread receives information from the main thread.
workerPort.onmessage = function(e) { workerPort.onmessage = function(e) {
// data carries the information sent by the main thread. // data carries the information sent by the main thread.
...@@ -2176,13 +2168,11 @@ Configuration of the **build-profile.json5** file: ...@@ -2176,13 +2168,11 @@ Configuration of the **build-profile.json5** file:
``` ```
### Stage Model ### Stage Model
```js ```js
// main.js (The following assumes that the workers directory and pages directory are at different levels.) // Main thread (The following assumes that the workers directory and pages directory are at different levels.)
import worker from '@ohos.worker'; import worker from '@ohos.worker';
// Create a Worker instance in the main thread. // Create a Worker instance in the main thread.
const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts");
// Create either a .json or .ts file.
// const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js");
// The main thread transfers information to the worker thread. // The main thread transfers information to the worker thread.
workerInstance.postMessage("123"); workerInstance.postMessage("123");
...@@ -2191,14 +2181,14 @@ workerInstance.postMessage("123"); ...@@ -2191,14 +2181,14 @@ workerInstance.postMessage("123");
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// data carries the information sent by the worker thread. // data carries the information sent by the worker thread.
let data = e.data; let data = e.data;
console.log("main.js onmessage"); console.log("main thread onmessage");
// Terminate the Worker instance. // Terminate the Worker instance.
workerInstance.terminate(); workerInstance.terminate();
} }
// Call onexit(). // Call onexit().
workerInstance.onexit = function() { workerInstance.onexit = function() {
console.log("main.js terminate"); console.log("main thread terminate");
} }
``` ```
```js ```js
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册