HarmonyOS Delay Tasks: 3 Tips to Make Background Scheduling "Smarter" ⏰
Hi, I'm Xiao L! In HarmonyOS development, delay tasks act like a "smart butler"—they can automatically trigger based on conditions like network status and battery level, avoiding resource waste. Today, I'll teach you three tricks to master delay task scheduling!
1. Delay Tasks: The "Smart Switch" for Conditional Triggering 🔌
Core Scenarios
Data-Saving Sync: Update data only when connected to Wi-Fi
Charging-Time Work: Automatically back up large files when connected to a charger
Five Key Trigger Conditions
Condition Type
Optional Values/Ranges
Sample Code
Network Type
WIFI/CELLULAR/NONE
networkType: NetworkType.WIFI
Battery Level
0-100 (percentage)
batteryLevel: 30 (trigger below 30%)
Charging Status
WIRELESS/USB/NONE
chargerType: ChargingType.USB
Storage Space
>1GB/<500MB, etc.
storageFree: 1024 (unit: MB)
Scheduled Task
Absolute time/periodic time
triggerAt: 1690000000 (timestamp)
2. Hands-On: Trigger Data Backup via "Wi-Fi + Charging"
Step 1: Define Task Conditions
import{WorkInfo,NetworkType,ChargingType}from'@ohos.workScheduler';constbackupWork:WorkInfo={workId:1001,// Unique identifier bundleName:'com.example.backup',abilityName:'BackupTaskAbility',networkType:NetworkType.WIFI,// Only in Wi-Fi environment chargerType:ChargingType.WIRELESS,// Only when wirelessly charging delay:300,// Delay 300 seconds after conditions are met (avoids immediate resource contention) repeatInterval:86400,// Execute once daily };
Step 2: Start Task Scheduling
functionscheduleBackup(){try{workScheduler.startWork(backupWork);console.log('Backup task scheduled, waiting for conditions to trigger');}catch (error){if (error.code===1001){console.log('Task already exists, no need to reschedule');}}}
Step 3: Handle Task Logic (in ExtensionAbility)
exportdefaultclassBackupTaskAbility{onStart(workInfo:WorkInfo){if (workInfo.workId===1001){this.performBackup();// Execute backup logic }}privateasyncperformBackup(){// Double-check network and charging status constisWifi=awaitcheckNetworkType(NetworkType.WIFI);constisCharging=awaitcheckChargingStatus();if (isWifi&&isCharging){awaitbackupToCloud();// Perform cloud backup workScheduler.stopWork(workInfo.workId);// Free resources after task completion }}}
3. System Scheduling: The "Backstage" of Resource Optimization 🧠
Top comments (0)