跟着官网的延迟任务文档实现的demo,在模拟器运行一直无法回调任务
申请延长服务后,log输出服务申请成功,但一直未有回调输出,使用 hdc 检测也为发现有注册的延迟任务,请帮大神帮看看是哪里出了问题
// ./entryworkschedulerextability/EntryWorkSchedulerExtAbility.ets
import hilog from '@ohos.hilog';
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
import workScheduler from '@ohos.resourceschedule.workScheduler';
export default class WorkSchedulerExtension extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo: workScheduler.WorkInfo) {
hilog.info(0, 'testTag', '%{public}s',
'WorkSchedulerExtensionAbility onWorkStart, workInfo = ' + JSON.stringify(workInfo));
}
onWorkStop(workInfo: workScheduler.WorkInfo) {
hilog.info(0, 'testTag', '%{public}s',
'WorkSchedulerExtensionAbility onWorkStop, workInfo = ' + JSON.stringify(workInfo));
}
};Index
import workScheduler from '@ohos.resourceschedule.workScheduler';
import { BusinessError } from '@kit.BasicServicesKit'
import hilog from '@ohos.hilog';
let workInfo: workScheduler.WorkInfo = {
workId: 1,
bundleName: 'com.example.application',
abilityName: 'WorkSchedulerExtension',
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
};
@Entry
@Component
struct Index {
@State currentCount: number = 0;
@State lastExecuteTime: string = '暂无';
@State isTaskRunning: boolean = false;
// 启动任务
private async startDelayTask() {
try {
workScheduler.startWork(workInfo);
this.isTaskRunning = true;
console.info('延迟任务申请成功');
hilog.info(0, 'testTag', '🚀 延迟任务申请成功 startWork ');
} catch (error) {
hilog.error(0, 'testTag', `延迟任务申请失败: code is ${(error as BusinessError).code}, message is ${(error as BusinessError).message}`);
}
}
// 停止任务的方法
private async stopDelayTask() {
try {
// 先检查任务是否存在
const workStatus = await workScheduler.getWorkStatus(1);
if (workStatus) {
workScheduler.stopWork(workInfo, true);
this.isTaskRunning = false;
hilog.info(0, 'testTag', '🚀 已停止存在的延迟任务 stopWork ');
}
} catch (error) {
// 如果任务不存在会抛出异常,这是正常的
hilog.error(0, 'testTag', '没有找到需要停止的任务,继续执行');
}
}
// 获取延迟任务状态
private async checkTaskStatus() {
try {
const workStatus = await workScheduler.getWorkStatus(1);
// 显示任务信息
hilog.info(0, 'testTag', `🚀 延迟任务状态checkTaskStatus: ${JSON.stringify({
workId: workStatus.workId,
bundleName: workStatus.bundleName,
abilityName: workStatus.abilityName,
isRepeat: workStatus.isRepeat,
repeatCycleTime: `${workStatus.repeatCycleTime}ms`
})}`);
} catch (error) {
hilog.error(0, 'testTag', `获取任务状态失败: ${JSON.stringify(error)}`);
}
}
// 获取所有延迟任务
private async getAllTasks() {
try {
const allWorks = await workScheduler.obtainAllWorks();
hilog.info(0, 'testTag', `🚀 所有延迟任务getAllTasks: ${JSON.stringify(allWorks)}`);
hilog.info(0, 'testTag', `🚀 任务数量: ${allWorks.length}`);
} catch (error) {
hilog.error(0, 'testTag', `获取所有任务失败: ${JSON.stringify(error)}`);
}
}
build() {
Column() {
Column({ space: 15 }) {
Text(this.isTaskRunning ? '延迟任务运行中' : '延迟任务已停止')
.fontSize(16)
.fontColor(this.isTaskRunning ? Color.Green : Color.Red)
}
.alignItems(HorizontalAlign.Center)
.padding(20)
.backgroundColor(Color.White)
.borderRadius(10)
.margin({ left: 20, right: 20 })
Column({ space: 10 }) {
Button(this.isTaskRunning ? '停止延迟任务' : '启动延迟任务')
.width('80%')
.backgroundColor(this.isTaskRunning ? Color.Red : Color.Green)
.onClick(() => {
if (this.isTaskRunning) {
this.stopDelayTask();
} else {
this.startDelayTask();
}
})
Button('检查任务状态')
.width('80%')
.backgroundColor(Color.Orange)
.onClick(() => {
this.checkTaskStatus();
})
Button('查看所有任务')
.width('80%')
.backgroundColor(Color.Brown)
.onClick(() => {
this.getAllTasks();
})
}
}
.width('100%')
.height('100%')
.backgroundColor('#F5F5F5')
.justifyContent(FlexAlign.Center) // 添加垂直居中对齐
.alignItems(HorizontalAlign.Center) // 添加水平居中对齐
}
}module.json5
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
],
"extensionAbilities": [
{
"name": "EntryWorkSchedulerExtAbility",
"srcEntry": "./ets/entryworkschedulerextability/EntryWorkSchedulerExtAbility.ets",
"type": "workScheduler"
}
]
}
}

2
浏览251 发布于2025-06-02 12:14广西
全部评论
最多点赞
最新发布
最早发布
写回答
所见即所得编辑器, editor1
工具栏
0/50000
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
了解社区公约,与您携手共创和谐专业的开发者社区。







































苏公安网备 32011402010933号