Files
红袍小恶魔 4ef62b5a42 重构AVSessionSysEvent与AVSessionStorageEvent共享Timer实例
新增AVSessionTimerHolder单例,持有单个Utils::Timer实例(EventStatisticTimer),
让AVSessionSysEvent与AVSessionStorageEvent的周期任务复用同一后台线程,
避免每个周期任务各起一个线程。

Utils::Timer::Register基于进程级单调递增计数器返回唯一timerId,
Unregister按id精确删除互不影响,共享单例方案可行。

主要改动:
- 新增AVSessionTimerHolder(utils/include、utils/src),Register失败时
  将正数错误码TIMER_ERR_DEAL_FAILED与0统一映射为0返回,修正原先
  static_cast<int32_t>(timerId)<0永远不成立导致假成功的bug。
- AVSessionSysEvent/AVSessionStorageEvent改为通过holder注册任务,
  不再各自创建Utils::Timer实例;Unregister/Shutdown用CHECK_AND_RETURN_LOG
  提前返回降低圈复杂度。
- STORAGE_EVENT_INIT/UNINIT、HISYSEVENT_UNREGISTER去掉调用括号,
  与已有HISYSEVENT_REGITER风格保持一致。
- 补充TimerHolder相关UT,覆盖懒加载Setup、复用、Unregister/Shutdown
  早返回与幂等等分支;修正avsession_storage_event_test.cpp末尾重复#endif
  的编译错误。

Co-Authored-By: Agent
Signed-off-by: 红袍小恶魔 <luyuchen3@huawei.com>
2026-07-01 17:31:09 +08:00

53 lines
1.7 KiB
C++

/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_AVSESSION_TIMER_HOLDER_H
#define OHOS_AVSESSION_TIMER_HOLDER_H
#ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
#include <memory>
#include <mutex>
#include "timer.h"
#endif
namespace OHOS::AVSession {
#ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
// Shared Utils::Timer so multiple periodic tasks reuse one thread.
class AVSessionTimerHolder {
public:
static AVSessionTimerHolder& GetInstance();
// Returns timerId (>0) for Unregister, or 0 on failure. intervalMs must be > 0.
uint32_t Register(const Utils::Timer::TimerCallback& callback, uint32_t intervalMs);
void Unregister(uint32_t timerId);
void Shutdown();
private:
AVSessionTimerHolder();
~AVSessionTimerHolder();
AVSessionTimerHolder(const AVSessionTimerHolder&) = delete;
AVSessionTimerHolder& operator=(const AVSessionTimerHolder&) = delete;
std::unique_ptr<Utils::Timer> timer_;
std::mutex lock_;
static constexpr uint32_t TIMER_REGISTER_FAILED = 65547;
};
#else
class AVSessionTimerHolder {};
#endif
} // namespace OHOS::AVSession
#endif // OHOS_AVSESSION_TIMER_HOLDER_H