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 16 #ifndef NATIVE_RDB_DELAY_NOTIFY_H 17 #define NATIVE_RDB_DELAY_NOTIFY_H 18 #include <atomic> 19 #include <chrono> 20 #include <map> 21 #include <string> 22 #include <functional> 23 #include <memory> 24 #include "rdb_types.h" 25 #include "executor_pool.h" 26 namespace OHOS::NativeRdb { 27 class DelayNotify { 28 public: 29 using Task = std::function<int(const DistributedRdb::RdbChangedData &, const DistributedRdb::RdbNotifyConfig &)>; 30 using Time = std::chrono::steady_clock::time_point; 31 DelayNotify(); 32 ~DelayNotify(); 33 void SetExecutorPool(std::shared_ptr<ExecutorPool> pool); 34 void SetTask(Task task); 35 void UpdateNotify(const DistributedRdb::RdbChangedData &changedData, bool isFull = false); 36 void SetAutoSyncInterval(uint32_t autoSyncInterval); 37 void Pause(); 38 void Resume(); 39 private: 40 static constexpr uint32_t AUTO_SYNC_INTERVAL = 200; 41 static constexpr uint32_t MAX_NOTIFY_INTERVAL = 5000; 42 static constexpr uint32_t SERVICE_INTERVAL = 10000; 43 bool isInitialized_ = false; 44 bool isFull_ = false; 45 Time lastTimePoint_; 46 std::atomic_int32_t pauseCount_; 47 ExecutorPool::TaskId delaySyncTaskId_ = ExecutorPool::INVALID_TASK_ID; 48 Task task_; 49 std::shared_ptr<ExecutorPool> pool_; 50 std::mutex mutex_; 51 DistributedRdb::RdbChangedData changedData_; 52 53 void StartTimer(); 54 void StopTimer(); 55 void ExecuteTask(); 56 void RestoreDefaultSyncInterval(); 57 uint32_t autoSyncInterval_ = AUTO_SYNC_INTERVAL; 58 }; 59 60 class PauseDelayNotify { 61 public: 62 explicit PauseDelayNotify(std::shared_ptr<DelayNotify> delayNotifier); 63 ~PauseDelayNotify(); 64 private: 65 static constexpr uint32_t AUTO_SYNC_MAX_INTERVAL = 3000; 66 std::shared_ptr<DelayNotify> delayNotifier_; 67 }; 68 } 69 #endif // NATIVE_RDB_DELAY_NOTIFY_H