DEV Community

SameX
SameX

Posted on

Analysis of Short-term Tasks and Long-term Tasks: The Basis of HarmonyOS Next Background Development

This article aims to deeply explore the technical details of Huawei's HarmonyOS Next system (as of API 12 currently) and is summarized based on actual development practices. It is mainly used as a carrier for technical sharing and exchange. Inevitable errors and omissions may exist. Colleagues are welcome to put forward valuable opinions and questions for common progress. This article is original content. Any form of reprint must indicate the source and original author.

Background tasks are an indispensable part of application development. They can allow applications to perform some time-consuming tasks in the background, such as saving status, downloading files, playing music, etc. HarmonyOS Next provides rich background task management functions. Among them, short-term tasks and long-term tasks are the most basic and commonly used two types. This article will deeply analyze short-term tasks and long-term tasks to help us better understand and use these functions in daily development.

Overview and application conditions of short-term tasks

Short-term tasks are suitable for tasks with high real-time requirements and short duration in the background, such as saving status, sending messages, making network requests, etc. Developers can apply for short-term tasks through the requestSuspendDelay interface and set up a callback function to handle the situation where the task times out.

Application conditions:

  • The application needs to apply for a short-term task in the foreground or within the onBackground callback. Otherwise, the application will fail.
  • An application can apply for a maximum of 3 short-term tasks at the same time.
  • The daily quota (within 24 hours) is 10 minutes by default. The single quota is up to 3 minutes. When the battery is low, the single quota is 1 minute by default.
  • After the task is completed, the application needs to actively cancel the short-term task. Otherwise, it will affect the remaining quota of the short-term task of the application on that day.
  • When the short-term task is about to time out, the system will callback the application. The application needs to cancel the short-term task. If it is not canceled after timeout, the system will terminate the corresponding application process.

Resource quota and quota management of short-term tasks

To ensure the rational use of device resources, the system will impose resource quota restrictions on short-term tasks. Each application will have a certain short-term task quota. After the quota is exhausted, no more short-term tasks can be applied for. Developers can query the remaining time of the short-term task of the current application through the getRemainingDelayTime interface and decide whether to continue executing other tasks according to the remaining time.

Quota calculation:

  • Only when the application is in the background, the short-term tasks under the application are timed.
  • For short-term tasks in the same period under the same application, the timing is not repeated.

Code example:

import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
function requestSuspendDelay() {
  let myReason = 'test requestSuspendDelay'; // Reason for application
  let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
    // Callback function. When the application's short-term task is about to time out, the application is called back through this function to perform some cleanup and annotation work and cancel the short-term task.
    console.info('suspend delay task will timeout');
    backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId);
  });
}
function getRemainingDelayTime() {
  backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res: number) => {
    console.info('Succeeded in getting remaining delay time.');
    console.info(`Remaining delay time: ${res} seconds`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`);
  });
}
Enter fullscreen mode Exit fullscreen mode

Application scenarios and implementation processes of long-term tasks

Long-term tasks are suitable for tasks that run in the background for a long time, such as music playback, navigation, device connection, location tracking, etc. Developers need to create a ContinuousTaskExtensionAbility to carry long-term tasks and implement the onContinuousTaskStart and onContinuousTaskStop callback functions to handle the logic of task start and end respectively.

Implementation process:

  1. Create a ContinuousTaskExtensionAbility and implement the lifecycle callback function.
  2. Start the long-term task through the backgroundTaskManager.startContinuousTask interface.
  3. Execute the task logic in the onContinuousTaskStart callback.
  4. Stop the task logic in the onContinuousTaskStop callback.

Code example:

import { ContinuousTaskExtensionAbility, backgroundTaskManager } from '@kit.BackgroundTasksKit';
export default class MyContinuousTaskExtensionAbility extends ContinuousTaskExtensionAbility {
  onContinuousTaskStart(workInfo: backgroundTaskManager.WorkInfo) {
    console.info(`onContinuousTaskStart, workInfo = ${JSON.stringify(workInfo)}`);
    // Start executing long-term task logic
  }
  onContinuousTaskStop(workInfo: backgroundTaskManager.WorkInfo) {
    console.info(`onContinuousTaskStop, workInfo is ${JSON.stringify(workInfo)}`);
    // Stop executing long-term task logic
  }
}
Enter fullscreen mode Exit fullscreen mode

Task timeout management and system callback

To prevent long-term tasks from occupying system resources for a long time, the system will perform timeout management on long-term tasks. Developers need to set the timeout time in the onContinuousTaskStart callback and stop the task through the backgroundTaskManager.stopContinuousTask interface after timeout.

Code example:

import { ContinuousTaskExtensionAbility, backgroundTaskManager } from '@kit.BackgroundTasksKit';
export default class MyContinuousTaskExtensionAbility extends ContinuousTaskExtensionAbility {
  onContinuousTaskStart(workInfo: backgroundTaskManager.WorkInfo) {
    console.info(`onContinuousTaskStart, workInfo = ${JSON.stringify(workInfo)}`);
    // Start executing long-term task logic
    // Set the timeout time, for example, 5 minutes
    setTimeout(() => {
      console.info('Continuous task timeout, stopping task...');
      backgroundTaskManager.stopContinuousTask(this.continuousTaskId);
    }, 5 * 60 * 1000);
  }
  onContinuousTaskStop(workInfo: backgroundTaskManager.WorkInfo) {
    console.info(`onContinuousTaskStop, workInfo is ${JSON.stringify(workInfo)}`);
    // Stop executing long-term task logic
  }
}
Enter fullscreen mode Exit fullscreen mode

Summary

Short-term tasks and long-term tasks are the basis of HarmonyOS Next background development. They are respectively suitable for background tasks in different scenarios. We need to choose the appropriate background task type according to actual needs and apply it in application development combined with specific development scenarios. At the same time, we also need to pay attention to the resource quota and system constraints of background tasks to avoid excessive consumption of device resources.

Top comments (0)