Master HarmonyOS Background Tasks: Transient, Continuous, Deferred & Reminder
This article explains the HarmonyOS NEXT Background Tasks Kit, detailing its four task types—Transient, Continuous, Deferred, and Agent‑powered Reminder—along with their characteristics, typical use cases, and complete ArkTS code examples for each scenario.
Background Tasks Kit Overview
The HarmonyOS NEXT Background Tasks Kit is a framework that lets developers schedule and manage background work efficiently, reducing power consumption, improving user experience, and supporting various task lifetimes.
Task Types and Characteristics
Transient Task : High real‑time requirement, short execution time; suitable for state saving, message sending, network requests.
Continuous Task : Runs for an extended period; ideal for music playback, navigation, device connection, location tracking.
Deferred Task : Triggered under specific conditions; used for periodic email sync, data download when network is available.
Agent‑powered Reminder : System‑level reminder that can launch an ability; fits countdowns, alarms, calendar events.
Typical Application Scenarios
Music Playback : Use a Continuous Task to keep audio playing when the app is backgrounded.
Navigation : Continuous Task maintains navigation updates even when the screen is off.
File Download : Continuous Task ensures large files continue downloading in the background.
Email Sync : Deferred Task synchronizes mail when a network connection is present.
Transient Task Example
The following ArkTS code demonstrates how to request a short‑lived (Transient) task, perform a computation, and cancel the task when it is about to time out.
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
@Entry
@Component
struct Index {
@State message: string = 'Click button to calculate.';
private requestId: number = 0;
// Request a transient task
requestSuspendDelay() {
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay('compute', () => {
console.info('Request suspension delay will time out.');
this.cancelSuspendDelay();
});
this.requestId = delayInfo.requestId;
} catch (error) {
console.error(`requestSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}
}
// Cancel the transient task
cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(this.requestId);
console.info('Request suspension delay cancel.');
}
// A dummy heavy computation
computeTask(times: number): number {
let start = new Date().getTime();
let a = 1, b = 1, c = 1;
for (let i = 0; i < times; i++) {
a = a * Math.random() + b * Math.random() + c * Math.random();
b = a * Math.random() + b * Math.random() + c * Math.random();
c = a * Math.random() + b * Math.random() + c * Math.random();
}
let end = new Date().getTime();
return end - start;
}
// Click handler
clickCallback = () => {
this.requestSuspendDelay();
let timeCost = this.computeTask(50000000);
this.message = `Total time costed = ${timeCost} ms.`;
this.cancelSuspendDelay();
}
// UI layout
build() {
Column() {
Row() { Text(this.message) }
Row() {
Button('开始计算').onClick(this.clickCallback)
.width('100%')
.justifyContent(FlexAlign.Center);
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center);
}
}
}The code imports the background task manager, defines a component with state, requests a transient task, runs a heavy calculation, displays the elapsed time, and ensures the task is cancelled when finished.
Continuous Task Example
This example shows how to start and stop a long‑running (Continuous) task, which is useful for scenarios like music playback or navigation.
import { backgroundTaskManager } from '@ohos.resourceschedule.backgroundTaskManager';
import { wantAgent } from '@ohos.app.ability.wantAgent';
@Entry
@Component
struct Index {
@State message: string = 'ContinuousTask';
private context: Context = getContext(this);
// Start a continuous task
startContinuousTask() {
let wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [{ bundleName: "com.example.myapplication", abilityName: "MainAbility" }],
actionType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj)
.then(() => console.info("Operation startBackgroundRunning succeeded"))
.catch((error: BusinessError) => console.error(`Failed to startBackgroundRunning. code is ${error.code} message is ${error.message}`));
});
}
// Stop the continuous task
stopContinuousTask() {
backgroundTaskManager.stopBackgroundRunning(this.context)
.then(() => console.info(`Succeeded in operationing stopBackgroundRunning.`))
.catch((err: BusinessError) => console.error(`Failed to stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`));
}
// UI layout
build() {
Row() {
Column() {
Text("Index").fontSize(50).fontWeight(FontWeight.Bold);
Button('申请长时任务')
.type(ButtonType.Capsule)
.margin({ top: 10 })
.backgroundColor('#0D9FFB')
.width(250)
.height(40)
.onClick(() => this.startContinuousTask());
Button('取消长时任务')
.type(ButtonType.Capsule)
.margin({ top: 10 })
.backgroundColor('#0D9FFB')
.width(250)
.height(40)
.onClick(() => this.stopContinuousTask());
}.width('100%');
}.height('100%');
}
}The snippet creates a WantAgent to describe the ability to launch, then starts a background running mode (audio recording) and provides UI buttons to start or stop the task.
Deferred Task Example
This example uses the WorkScheduler to schedule a task that runs only when certain conditions (Wi‑Fi, battery level) are met.
import workScheduler from '@ohos.resourceschedule.workScheduler';
import { BusinessError } from '@ohos.base';
// Configure the work info
const workInfo: workScheduler.WorkInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: 'com.example.application',
abilityName: 'MyWorkSchedulerExtensionAbility',
batteryLevel: 30,
chargerType: workScheduler.ChargingType.CHARGER_TYPE_NONE,
isPersisted: true
};
// Request a deferred task
function requestDeferredTask() {
try {
workScheduler.startWork(workInfo);
console.info(`startWork success`);
} catch (error) {
console.error(`startWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}
}
// Cancel a deferred task
function cancelDeferredTask() {
try {
workScheduler.stopWork(workInfo);
console.info(`stopWork success`);
} catch (error) {
console.error(`stopWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}
}
export { requestDeferredTask, cancelDeferredTask };The code defines a WorkInfo object with network, battery, and persistence settings, then provides functions to start and stop the deferred work.
Agent‑Powered Reminder Example
This snippet shows how to publish a timer‑based reminder that can launch a specific ability when the timer expires.
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Define a timer reminder
let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER,
triggerTimeInSeconds: 10,
actionButton: [{ title: 'close', type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE }],
wantAgent: { pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' },
maxScreenWantAgent: { pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' },
title: 'this is title',
content: 'this is content',
expiredContent: 'this reminder has expired',
notificationId: 100,
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
};
// Publish the reminder
reminderAgentManager.publishReminder(targetReminderAgent)
.then((res: number) => {
console.info('Succeeded in publishing reminder.');
let reminderId: number = res; // ID of the published reminder
})
.catch((err: BusinessError) => {
console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
});The example creates a reminder that fires after ten seconds, includes a close button, and specifies the ability to be launched. It then publishes the reminder and handles success or failure.
Conclusion
HarmonyOS NEXT’s Background Tasks Kit provides four distinct task models—Transient, Continuous, Deferred, and Agent‑powered Reminder—each suited to different real‑world scenarios such as short‑lived UI updates, long‑running media playback, conditional data sync, or timed notifications. By following the provided ArkTS examples, developers can integrate these capabilities into their apps to improve reliability, conserve battery, and deliver a smoother user experience.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architecture Stack
Dedicated to original, practical tech insights—from skill advancement to architecture, front‑end to back‑end, the full‑stack path, with Wei Ge guiding you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
