1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 17import { BusinessError } from '@ohos.base'; 18import util from '@ohos.util'; 19import hiTraceMeter from '@ohos.hiTraceMeter'; 20import taskpool from '@ohos.taskpool'; 21 22const totalTimes: number = 50000000; // 循环次数 23const calculateResult: string = 'Total time costed = %s ms.'; // 文本格式 24 25@Component 26export struct TransientTaskView { 27 @State message: string = 'Click button to calculate.'; 28 private requestId: number = 0; 29 30 // 申请短时任务 31 requestSuspendDelay() { 32 try { 33 let delayInfo = backgroundTaskManager.requestSuspendDelay('compute', () => { 34 console.info('Request suspension delay will time out.'); 35 // 任务即将超时,取消短时任务 36 this.cancelSuspendDelay(); 37 }) 38 this.requestId = delayInfo.requestId; 39 } catch (error) { 40 console.error(`requestSuspendDelay failed. message is ${(error as BusinessError).message}`); 41 } 42 } 43 44 // 取消短时任务 45 cancelSuspendDelay() { 46 backgroundTaskManager.cancelSuspendDelay(this.requestId); 47 console.info('Request suspension delay cancel.'); 48 } 49 50 // 点击回调 51 clickCallback = () => { 52 this.requestSuspendDelay(); 53 this.message = 'calculating'; 54 hiTraceMeter.startTrace('computerTask', 0); 55 let task: taskpool.Task = new taskpool.Task(computeTask, totalTimes); 56 taskpool.execute(task, taskpool.Priority.HIGH).then((res: Object) => { 57 this.message = util.format(calculateResult, res.toString()); 58 hiTraceMeter.finishTrace('computerTask', 0); 59 this.cancelSuspendDelay(); 60 }) 61 } 62 63 build() { 64 Column() { 65 Row() { 66 Text(this.message) 67 } 68 69 Row() { 70 Button('开始计算') 71 .onClick(this.clickCallback) 72 } 73 .width('100%') 74 .justifyContent(FlexAlign.Center) 75 } 76 .width('100%') 77 .height('100%') 78 .justifyContent(FlexAlign.Center) 79 } 80} 81 82// 计算任务 83@Concurrent 84function computeTask(times: number): number { 85 let start: number = new Date().getTime(); 86 let a: number = 1; 87 let b: number = 1; 88 let c: number = 1; 89 90 for (let i: number = 0; i < times; i++) { 91 a = a * Math.random() + b * Math.random() + c * Math.random(); 92 b = a * Math.random() + b * Math.random() + c * Math.random(); 93 c = a * Math.random() + b * Math.random() + c * Math.random(); 94 } 95 let end: number = new Date().getTime(); 96 return end - start; 97}