!40 增加时间时区获取接口和分钟tick通知

Merge pull request !40 from guduhanyan/master
This commit is contained in:
openharmony_ci
2021-12-24 07:58:37 +00:00
committed by Gitee
16 changed files with 753 additions and 141 deletions
@@ -28,6 +28,47 @@ declare namespace systemTime {
*/
function setTime(time : number, callback : AsyncCallback<void>) : void;
function setTime(time : number) : Promise<void>;
/**
* Obtains the number of milliseconds that have elapsed since the Unix epoch.
* @since 8
*/
function getCurrentTime(callback: AsyncCallback<number>): void;
function getCurrentTime(): Promise<number>;
/**
* Obtains the number of nanoseconds that have elapsed since the Unix epoch.
* @since 8
*/
function getCurrentTimeNs(callback: AsyncCallback<number>): void;
function getCurrentTimeNs(): Promise<number>;
/**
* Obtains the number of milliseconds elapsed since the system was booted, not including deep sleep time.
* @since 8
*/
function getRealActiveTime(callback: AsyncCallback<number>): void;
function getRealActiveTime(): Promise<number>;
/**
* Obtains the number of nanoseconds elapsed since the system was booted, not including deep sleep time.
* @since 8
*/
function getRealActiveTimeNs(callback: AsyncCallback<number>): void;
function getRealActiveTimeNs(): Promise<number>;
/**
* Obtains the number of milliseconds elapsed since the system was booted, including deep sleep time.
* @since 8
*/
function getRealTime(callback: AsyncCallback<number>): void;
function getRealTime(): Promise<number>;
/**
* Obtains the number of nanoseconds elapsed since the system was booted, including deep sleep time.
* @since 8
*/
function getRealTimeNs(callback: AsyncCallback<number>): void;
function getRealTimeNs(): Promise<number>;
/**
* Sets the system time.
@@ -37,6 +78,13 @@ declare namespace systemTime {
function setDate(date: Date, callback: AsyncCallback<void>): void;
function setDate(date: Date): Promise<void>;
/**
* Obtains the system date.
* @since 8
*/
function getDate(callback: AsyncCallback<Date>): void;
function getDate(): Promise<Date>;
/**
* Sets the system time zone.
* @permission ohos.permission.SET_TIME_ZONE
@@ -44,6 +92,13 @@ declare namespace systemTime {
*/
function setTimezone(timezone: string, callback: AsyncCallback<void>): void;
function setTimezone(timezone: string): Promise<void>;
/**
* Obtains the system time zone.
* @since 8
*/
function getTimezone(callback: AsyncCallback<string>): void;
function getTimezone(): Promise<string>;
}
export default systemTime;
@@ -269,13 +269,470 @@ napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info)
}
}
napi_value ParseParametersGet(const napi_env &env, const napi_value (&argv)[SET_TIMEZONE_MAX_PARA],
const size_t &argc, napi_ref &callback)
{
NAPI_ASSERT(env, argc >= SET_TIMEZONE_MAX_PARA - 1, "Wrong number of arguments");
napi_valuetype valueType = napi_undefined;
if (argc == 1) {
NAPI_CALL(env, napi_typeof(env, argv[0], &valueType));
NAPI_ASSERT(env, valueType == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[0], 1, &callback);
}
return TimeNapiGetNull(env);
}
napi_value JSSystemTimeGetCurrentTime(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetCurrentTime", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeMs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_int64(env, asyncContext->time, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetCurrentTimeNs(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetCurrentTimeNs", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeNs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_int64(env, asyncContext->time, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetRealActiveTime(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetRealActiveTime", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetMonotonicTimeMs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_int64(env, asyncContext->time, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetRealActiveTimeNs(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetRealActiveTimeNs", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetMonotonicTimeNs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_int64(env, asyncContext->time, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetRealTime(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetRealTime", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetBootTimeMs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_int64(env, asyncContext->time, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetRealTimeNs(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetRealTimeNs", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetBootTimeNs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_int64(env, asyncContext->time, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetDate(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetDate", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeMs();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->time < 0) {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
std::string str = "new Date(" + std::to_string(asyncContext->time) + ");";
const char *scriptStr = str.c_str();
napi_value script = nullptr;
napi_create_string_utf8(env, scriptStr, strlen(scriptStr), &script);
napi_value result = nullptr;
napi_run_script(env, script, &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
napi_value JSSystemTimeGetTimeZone(napi_env env, napi_callback_info info)
{
size_t argc = SET_TIMEZONE_MAX_PARA;
napi_value argv[SET_TIMEZONE_MAX_PARA] = {0};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL));
napi_ref callback = nullptr;
if (ParseParametersGet(env, argv, argc, callback) == nullptr) {
return TimeJSParaError(env, callback);
}
AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env};
if (!asyncContext) {
return TimeJSParaError(env, callback);
}
TIME_HILOGI(TIME_MODULE_JS_NAPI, " jsgetTimezone start==");
napi_value promise = nullptr;
TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise);
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeGetTimeZone", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env,
nullptr,
resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
asyncContext->timeZone = TimeServiceClient::GetInstance()->GetTimeZone();
},
[](napi_env env, napi_status status, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
if (asyncContext->timeZone == "") {
asyncContext->errorCode = ERROR;
}
TimeCallbackPromiseInfo info;
info.isCallback = asyncContext->isCallback;
info.callback = asyncContext->callbackRef;
info.deferred = asyncContext->deferred;
info.errorCode = asyncContext->errorCode;
napi_value result = nullptr;
napi_create_string_utf8(env, asyncContext->timeZone.c_str(), asyncContext->timeZone.length(), &result);
TimeReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asyncContext->work);
if (asyncContext) {
delete asyncContext;
asyncContext = nullptr;
}
},
(void*)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
if (asyncContext->isCallback) {
return TimeNapiGetNull(env);
} else {
return promise;
}
}
EXTERN_C_START
napi_value SystemTimeExport(napi_env env, napi_value exports)
{
static napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("setTime", JSSystemTimeSetTime),
DECLARE_NAPI_FUNCTION("setDate", JSSystemTimeSetTime),
DECLARE_NAPI_FUNCTION("setTimezone", JSSystemTimeSetTimeZone)
DECLARE_NAPI_FUNCTION("setTimezone", JSSystemTimeSetTimeZone),
DECLARE_NAPI_FUNCTION("getCurrentTime", JSSystemTimeGetCurrentTime),
DECLARE_NAPI_FUNCTION("getCurrentTimeNs", JSSystemTimeGetCurrentTimeNs),
DECLARE_NAPI_FUNCTION("getRealActiveTime", JSSystemTimeGetRealActiveTime),
DECLARE_NAPI_FUNCTION("getRealActiveTimeNs", JSSystemTimeGetRealActiveTimeNs),
DECLARE_NAPI_FUNCTION("getRealTime", JSSystemTimeGetRealTime),
DECLARE_NAPI_FUNCTION("getRealTimeNs", JSSystemTimeGetRealTimeNs),
DECLARE_NAPI_FUNCTION("getDate", JSSystemTimeGetDate),
DECLARE_NAPI_FUNCTION("getTimeZone", JSSystemTimeGetTimeZone),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
return exports;
+11 -8
View File
@@ -24,11 +24,19 @@ config("time_service_config") {
"//third_party/json/include",
"//base/hiviewdfx/hilog/interfaces/native/innerkits/include",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb/include/",
"/foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk/include/",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk/include/",
]
}
ohos_shared_library("time_service") {
configs = [ "${time_utils_path}:utils_config" ]
public_configs = [
"//utils/native/base:utils_config",
"//third_party/jsoncpp:jsoncpp_public_config",
":time_service_config",
]
sources = [
"time_manager/src/itimer_info.cpp",
"time_manager/src/time_service.cpp",
@@ -36,6 +44,7 @@ ohos_shared_library("time_service") {
"time_manager/src/time_service_notify.cpp",
"time_manager/src/time_service_proxy.cpp",
"time_manager/src/time_service_stub.cpp",
"time_manager/src/time_tick_notify.cpp",
"time_manager/src/time_zone_info.cpp",
"time_manager/src/timer_call_back.cpp",
"time_manager/src/timer_call_back_proxy.cpp",
@@ -45,19 +54,13 @@ ohos_shared_library("time_service") {
"timer/src/timer_info.cpp",
"timer/src/timer_manager.cpp",
]
configs = [ "${time_utils_path}:utils_config" ]
public_configs = [
"//utils/native/base:utils_config",
"//third_party/jsoncpp:jsoncpp_public_config",
":time_service_config",
]
deps = [
"${time_utils_path}:time_utils",
"//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk:native_appdatafwk",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_preferences:native_preferences",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb",
"//third_party/jsoncpp:jsoncpp",
"//utils/native/base:utils",
]
+2 -1
View File
@@ -56,6 +56,8 @@ public:
int32_t GetThreadTimeNs(int64_t &times) override;
uint64_t CreateTimer(int32_t type, bool repeat, uint64_t interval, sptr<IRemoteObject> &timerCallback) override;
uint64_t CreateTimer(int32_t type, uint64_t windowLength, uint64_t interval, int flag,
std::function<void (const uint64_t)> Callback);
bool StartTimer(uint64_t timerId, uint64_t triggerTime) override;
bool StopTimer(uint64_t timerId) override;
bool DestroyTimer(uint64_t timerId) override;
@@ -89,7 +91,6 @@ private:
const std::string setTimePermName_ = "ohos.permission.SET_TIME";
const std::string setTimezonePermName_ = "ohos.permission.SET_TIME_ZONE";
const int rtc_id;
static std::shared_ptr<MiscServices::TimeServiceNotify> timeServiceNotify_;
static std::shared_ptr<AppExecFwk::EventHandler> serviceHandler_;
static std::shared_ptr<TimerManager> timerManagerHandler_;
};
@@ -15,6 +15,7 @@
#ifndef TIME_SERVICE_NOTIFY_H
#define TIME_SERVICE_NOTIFY_H
#include <singleton.h>
#include <common_event_publish_info.h>
#include <ohos/aafwk/content/want.h>
@@ -23,14 +24,14 @@
namespace OHOS {
namespace MiscServices {
class TimeServiceNotify {
class TimeServiceNotify : public DelayedSingleton<TimeServiceNotify> {
DECLARE_DELAYED_SINGLETON(TimeServiceNotify);
public:
TimeServiceNotify() = default;
~TimeServiceNotify() = default;
DISALLOW_COPY_AND_MOVE(TimeServiceNotify);
void RegisterPublishEvents();
void PublishTimeChanageEvents(int64_t eventTime);
void PublishTimeZoneChangeEvents(int64_t eventTime);
void PublishTimeTickEvents(int64_t eventTime);
private:
using IntentWant = OHOS::AAFwk::Want;
@@ -38,6 +39,7 @@ private:
sptr<IntentWant> timeChangeWant_;
sptr<IntentWant> timeZoneChangeWant_;
sptr<IntentWant> timeTickWant_;
sptr<OHOS::EventFwk::CommonEventPublishInfo> publishInfo_;
};
} // namespace MiscServices
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2021 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 TIME_TICK_NOTIFY_H
#define TIME_TICK_NOTIFY_H
#include <singleton.h>
namespace OHOS {
namespace MiscServices {
class TimeTickNotify : public DelayedSingleton<TimeTickNotify> {
DECLARE_DELAYED_SINGLETON(TimeTickNotify);
public:
DISALLOW_COPY_AND_MOVE(TimeTickNotify);
void Init();
void Callback(const uint64_t timerid);
void Stop();
private:
void StartTimer();
void RefreshNextTriggerTime();
uint64_t GetMillisecondsFromUTC(uint64_t UTCtimeNano);
uint64_t GetSecondsFromUTC(uint64_t UTCtimeNano);
uint64_t timerId_;
uint64_t nextTriggerTime_;
};
} // MiscServices
} // OHOS
#endif
@@ -32,10 +32,10 @@ namespace MiscServices {
struct zoneInfoEntry {
std::string ID;
std::string alias;
float utcOffsetHours;
int utcOffsetHours;
};
class TimeZoneInfo {
class TimeZoneInfo : public std::enable_shared_from_this<TimeZoneInfo> {
DECLARE_DELAYED_SINGLETON(TimeZoneInfo)
public:
bool GetTimezone(std::string &timezoneId);
@@ -43,8 +43,8 @@ public:
void Init();
private:
bool InitStorage();
bool SetOffsetToKernel(float offset);
bool GetOffsetById(const std::string timezoneId, float &offset);
bool SetOffsetToKernel(int offset);
bool GetOffsetById(const std::string timezoneId, int &offset);
bool GetTimezoneFromFile(std::string &timezoneId);
bool SaveTimezoneToFile(std::string timezoneId);
std::string curTimezoneId_;
+26 -24
View File
@@ -18,25 +18,27 @@
#include <unistd.h>
#include <sys/time.h>
#include <cerrno>
#include <chrono>
#include <mutex>
#include <dirent.h>
#include <cstring>
#include <fcntl.h>
#include <fstream>
#include <sstream>
#include <singleton.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>
#include "pthread.h"
#include "time_zone_info.h"
#include "time_common.h"
#include "time_tick_notify.h"
#include "system_ability.h"
#include "system_ability_definition.h"
#include "iservice_registry.h"
#include "time_service.h"
using namespace std::chrono;
namespace OHOS {
namespace MiscServices {
@@ -49,7 +51,6 @@ static const std::int32_t INIT_INTERVAL = 10000L;
static const uint32_t TIMER_TYPE_REALTIME_MASK = 1 << 0;
static const uint32_t TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
static const uint32_t TIMER_TYPE_EXACT_MASK = 1 << 2;
constexpr int MIN_TRIGGER_TIMES = 5000;
constexpr int INVALID_TIMER_ID = 0;
constexpr int MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
constexpr int NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
@@ -60,7 +61,6 @@ REGISTER_SYSTEM_ABILITY_BY_ID(TimeService, TIME_SERVICE_ID, true);
std::mutex TimeService::instanceLock_;
sptr<TimeService> TimeService::instance_;
std::shared_ptr<AppExecFwk::EventHandler> TimeService::serviceHandler_ = nullptr;
std::shared_ptr<MiscServices::TimeServiceNotify> TimeService::timeServiceNotify_ = nullptr;
std::shared_ptr<TimerManager> TimeService::timerManagerHandler_ = nullptr;
TimeService::TimeService(int32_t systemAbilityId, bool runOnCreate)
@@ -100,6 +100,7 @@ void TimeService::OnStart()
InitServiceHandler();
InitTimerHandler();
InitNotifyHandler();
DelayedSingleton<TimeTickNotify>::GetInstance()->Init();
DelayedSingleton<TimeZoneInfo>::GetInstance()->Init();
if (Init() != ERR_OK) {
auto callback = [=]() { Init(); };
@@ -131,7 +132,7 @@ void TimeService::OnStop()
return;
}
serviceHandler_ = nullptr;
timeServiceNotify_ = nullptr;
DelayedSingleton<TimeTickNotify>::GetInstance()->Stop();
state_ = ServiceRunningState::STATE_NOT_START;
TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop End.");
}
@@ -139,12 +140,7 @@ void TimeService::OnStop()
void TimeService::InitNotifyHandler()
{
TIME_HILOGI(TIME_MODULE_SERVICE, "InitNotify started.");
if (timeServiceNotify_ != nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, " Already init.");
return;
}
timeServiceNotify_ = std::make_shared<MiscServices::TimeServiceNotify>();
timeServiceNotify_->RegisterPublishEvents();
DelayedSingleton<TimeServiceNotify>::GetInstance()->RegisterPublishEvents();
}
void TimeService::InitServiceHandler()
@@ -241,6 +237,20 @@ uint64_t TimeService::CreateTimer(int32_t type, bool repeat, uint64_t interval,
uid);
}
uint64_t TimeService::CreateTimer(int32_t type, uint64_t windowLength, uint64_t interval, int flag,
std::function<void (const uint64_t)> Callback)
{
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
timerManagerHandler_ = TimerManager::Create();
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
return INVALID_TIMER_ID;
}
}
return timerManagerHandler_->CreateTimer(type, windowLength, interval, flag, Callback, 0);
}
bool TimeService::StartTimer(uint64_t timerId, uint64_t triggerTimes)
{
if (timerManagerHandler_ == nullptr) {
@@ -251,8 +261,7 @@ bool TimeService::StartTimer(uint64_t timerId, uint64_t triggerTimes)
return false;
}
}
uint64_t triggerTimesIn = (triggerTimes < MIN_TRIGGER_TIMES) ? MIN_TRIGGER_TIMES : triggerTimes;
auto ret = timerManagerHandler_->StartTimer(timerId, triggerTimesIn);
auto ret = timerManagerHandler_->StartTimer(timerId, triggerTimes);
if (!ret) {
TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
}
@@ -320,12 +329,8 @@ int32_t TimeService::SetTime(const int64_t time)
TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d.", ret);
return E_TIME_SET_RTC_FAILED;
}
int64_t currentTime = 0;
GetWallTimeMs(currentTime);
if (timeServiceNotify_ != nullptr) {
timeServiceNotify_->PublishTimeChanageEvents(currentTime);
}
auto currentTime = steady_clock::now().time_since_epoch().count();
DelayedSingleton<TimeServiceNotify>::GetInstance()->PublishTimeChanageEvents(currentTime);
return ERR_OK;
}
@@ -441,11 +446,8 @@ int32_t TimeService::SetTimeZone(const std::string timeZoneId)
TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
return E_TIME_DEAL_FAILED;
}
int64_t currentTime = 0;
GetWallTimeMs(currentTime);
if (timeServiceNotify_ != nullptr) {
timeServiceNotify_->PublishTimeZoneChangeEvents(currentTime);
}
auto currentTime = steady_clock::now().time_since_epoch().count();
DelayedSingleton<TimeServiceNotify>::GetInstance()->PublishTimeZoneChangeEvents(currentTime);
return ERR_OK;
}
@@ -25,6 +25,8 @@ using namespace OHOS::EventFwk;
namespace OHOS {
namespace MiscServices {
TimeServiceNotify::TimeServiceNotify() {};
TimeServiceNotify::~TimeServiceNotify() {};
void TimeServiceNotify::RegisterPublishEvents()
{
if (publishInfo_ != nullptr) {
@@ -36,6 +38,8 @@ void TimeServiceNotify::RegisterPublishEvents()
timeChangeWant_->SetAction(CommonEventSupport::COMMON_EVENT_TIME_CHANGED);
timeZoneChangeWant_ = new (std::nothrow)IntentWant();
timeZoneChangeWant_->SetAction(CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED);
timeTickWant_ = new (std::nothrow)IntentWant();
timeTickWant_->SetAction(CommonEventSupport::COMMON_EVENT_TIME_TICK);
}
void TimeServiceNotify::PublishEvents(int64_t eventTime, sptr<IntentWant> want)
@@ -61,5 +65,10 @@ void TimeServiceNotify::PublishTimeZoneChangeEvents(int64_t eventTime)
{
PublishEvents(eventTime, timeZoneChangeWant_);
}
void TimeServiceNotify::PublishTimeTickEvents(int64_t eventTime)
{
PublishEvents(eventTime, timeTickWant_);
}
} // MiscService
} // OHOS
@@ -0,0 +1,101 @@
/*
* Copyright (C) 2021 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.
*/
#include <chrono>
#include <thread>
#include <cinttypes>
#include "time_common.h"
#include "time_service_notify.h"
#include "timer_manager_interface.h"
#include "time_service.h"
#include "time_tick_notify.h"
using namespace std::chrono;
namespace OHOS {
namespace MiscServices {
namespace {
constexpr uint64_t SECOND_TO_MILESECOND = 1000;
constexpr uint64_t MINUTE_TO_MILLISECOND = 6000;
constexpr uint64_t NANO_TO_SECOND = 1000000000;
constexpr uint64_t NANO_TO_MILESECOND = 100000;
constexpr uint64_t SECOND_TO_MINUTE = 60;
}
TimeTickNotify::TimeTickNotify() {};
TimeTickNotify::~TimeTickNotify() {};
void TimeTickNotify::Init()
{
TIME_HILOGD(TIME_MODULE_SERVICE, "Tick notify start.");
int32_t timerType = ITimerManager::TimerType::ELAPSED_REALTIME;
auto callback = [this](uint64_t id) {
this->Callback(id);
};
timerId_ = TimeService::GetInstance()->CreateTimer(timerType, 0, 0, 0, callback);
TIME_HILOGD(TIME_MODULE_SERVICE, "Tick notify timerId: %{public}" PRId64 "", timerId_);
RefreshNextTriggerTime();
TIME_HILOGD(TIME_MODULE_SERVICE, "Tick notify triggertime: %{public}" PRId64 "", nextTriggerTime_);
TimeService::GetInstance()->StartTimer(timerId_, nextTriggerTime_);
}
void TimeTickNotify::Callback(const uint64_t timerId)
{
TIME_HILOGD(TIME_MODULE_SERVICE, "Tick notify timerId: %{public}" PRId64 "", timerId);
auto currentTime = steady_clock::now().time_since_epoch().count();
DelayedSingleton<TimeServiceNotify>::GetInstance()->PublishTimeTickEvents(currentTime);
timerId_ = timerId;
RefreshNextTriggerTime();
auto startFunc = [this]() {
this->StartTimer();
};
std::thread startTimerThread(startFunc);
startTimerThread.detach();
TIME_HILOGD(TIME_MODULE_SERVICE, "Tick notify triggertime: %{public}" PRId64 "", nextTriggerTime_);
}
void TimeTickNotify::RefreshNextTriggerTime()
{
uint64_t timeNowMilliseconds;
auto UTCTimeNano = system_clock::now().time_since_epoch().count();
auto BootTimeNano = steady_clock::now().time_since_epoch().count();
auto BootTimeMilli = BootTimeNano / NANO_TO_MILESECOND;
auto timeMilliseconds = GetMillisecondsFromUTC(UTCTimeNano);
auto timeSeconds = GetSecondsFromUTC(UTCTimeNano);
timeNowMilliseconds = timeSeconds * SECOND_TO_MILESECOND + timeMilliseconds;
nextTriggerTime_ = BootTimeMilli+ (MINUTE_TO_MILLISECOND - timeNowMilliseconds);
return ;
}
void TimeTickNotify::StartTimer()
{
TimeService::GetInstance()->StartTimer(timerId_, nextTriggerTime_);
}
void TimeTickNotify::Stop()
{
TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
TimeService::GetInstance()->DestroyTimer(timerId_);
}
uint64_t TimeTickNotify::GetMillisecondsFromUTC(uint64_t UTCtimeNano)
{
return (UTCtimeNano / NANO_TO_MILESECOND) % SECOND_TO_MILESECOND;
}
uint64_t TimeTickNotify::GetSecondsFromUTC(uint64_t UTCtimeNano)
{
return (UTCtimeNano / NANO_TO_SECOND) % SECOND_TO_MINUTE;
}
} // MiscServices
} // OHOS
+17 -18
View File
@@ -20,17 +20,16 @@ namespace OHOS {
namespace MiscServices {
namespace {
const std::string TIMEZONE_FILE_PATH = "/data/misc/zoneinfo/timezone.json";
static const int HOURS_TO_MINUTES = 60;
}
TimeZoneInfo::TimeZoneInfo()
{
std::vector<struct zoneInfoEntry> timezoneList = {
std::vector<struct zoneInfoEntry> timezoneList = {
{"Antarctica/McMurdo", "AQ", 12},
{"America/Argentina/Buenos_Aires", "AR", -3},
{"Australia/Sydney", "AU", 10},
{"America/Noronha", "BR", -2},
{"America/St_Johns", "CA", -2.5},
{"America/St_Johns", "CA", -3},
{"Africa/Kinshasa", "CD", 1},
{"America/Santiago", "CL", -3},
{"Asia/Shanghai", "CN", 8},
@@ -73,14 +72,14 @@ void TimeZoneInfo::Init()
{
TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
std::string timezoneId;
float gmtOffset;
int gmtOffset;
if (!InitStorage()) {
TIME_HILOGE(TIME_MODULE_SERVICE, "end, InitStorage failed.");
return;
}
if (!GetTimezoneFromFile(timezoneId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "end, GetTimezoneFromFile failed.");
return;
timezoneId = "Asia/Shanghai";
}
if (!GetOffsetById(timezoneId, gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "end, GetOffsetById failed.");
@@ -117,12 +116,11 @@ bool TimeZoneInfo::InitStorage()
bool TimeZoneInfo::SetTimezone(std::string timezoneId)
{
float gmtOffset;
int gmtOffset;
if (!GetOffsetById(timezoneId, gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timezone unsupport %{public}s.", timezoneId.c_str());
return false;
}
TIME_HILOGD(TIME_MODULE_SERVICE, "timezone :%{public}s , GMT Offset :%{public}f", timezoneId.c_str(), gmtOffset);
if (!SetOffsetToKernel(gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Set kernel failed.");
return false;
@@ -141,18 +139,19 @@ bool TimeZoneInfo::GetTimezone(std::string &timezoneId)
return true;
}
bool TimeZoneInfo::SetOffsetToKernel(float offsetHour)
bool TimeZoneInfo::SetOffsetToKernel(int offsetHour)
{
struct timezone tz{};
tz.tz_minuteswest = static_cast<int>(offsetHour * HOURS_TO_MINUTES);
tz.tz_dsttime = 0;
TIME_HILOGD(TIME_MODULE_SERVICE, "settimeofday, Offset hours :%{public}f , Offset minutes :%{public}d", offsetHour, tz.tz_minuteswest);
int result = settimeofday(NULL, &tz);
if (result < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday fail: %{public}d.", result);
return false;
std::stringstream TZstrs;
time_t timeNow;
TZstrs << "UTC-" << offsetHour;
(void)time(&timeNow);
if (setenv("TZ", TZstrs.str().data(), 1) == 0) {
tzset();
(void)time(&timeNow);
return true;
}
return true;
TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed %{public}s", TZstrs.str().data());
return false;
}
bool TimeZoneInfo::GetTimezoneFromFile(std::string &timezoneId)
@@ -188,7 +187,7 @@ bool TimeZoneInfo::SaveTimezoneToFile(std::string timezoneId)
return true;
}
bool TimeZoneInfo::GetOffsetById(const std::string timezoneId, float &offset)
bool TimeZoneInfo::GetOffsetById(const std::string timezoneId, int &offset)
{
auto itEntry = timezoneInfoMap_.find(timezoneId);
if (itEntry != timezoneInfoMap_.end()) {
@@ -31,6 +31,9 @@
namespace OHOS {
namespace MiscServices {
namespace {
constexpr uint64_t NANO_TO_MILESECOND = 100000;
}
class TimerInfoTest : public ITimerInfo {
public:
TimerInfoTest();
@@ -12,13 +12,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdlib>
#include <ctime>
#include <chrono>
#include "timer_info_test.h"
#include "time_service_test.h"
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::MiscServices;
using namespace std::chrono;
class TimeServiceTest : public testing::Test
{
@@ -52,11 +55,11 @@ void TimeServiceTest::TearDown(void)
*/
HWTEST_F(TimeServiceTest, SetTime001, TestSize.Level0)
{
struct timeval getTime;
struct timeval getTime {};
gettimeofday(&getTime, NULL);
int64_t time = (getTime.tv_sec + 1000) * 1000 + getTime.tv_usec / 1000;
if (time < 0) {
TIME_HILOGE(TIME_MODULE_CLIENT, "Time now invalid : %{public}" PRId64 "",time);
TIME_HILOGE(TIME_MODULE_CLIENT, "Time now invalid : %{public}" PRId64 "", time);
time = 1627307312000;
}
TIME_HILOGI(TIME_MODULE_CLIENT, "Time now : %{public}" PRId64 "",time);
@@ -71,15 +74,12 @@ HWTEST_F(TimeServiceTest, SetTime001, TestSize.Level0)
*/
HWTEST_F(TimeServiceTest, SetTimeZone001, TestSize.Level0)
{
struct timezone tz = {};
gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "Before set timezone, GMT offset in kernel : %{public}d", tz.tz_minuteswest);
time_t t;
(void)time(&t);
TIME_HILOGI(TIME_MODULE_CLIENT, "Time before: %{public}s", asctime(localtime(&t)));
std::string timeZoneSet("Asia/Shanghai");
bool result = TimeServiceClient::GetInstance()->SetTimeZone(timeZoneSet);
EXPECT_TRUE(result);
auto ret = gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "gettimeofday result : %{public}d", ret);
TIME_HILOGD(TIME_MODULE_CLIENT, "After set timezone, GMT offset minutes in kernel : %{public}d", tz.tz_minuteswest);
auto timeZoneRes = TimeServiceClient::GetInstance()->GetTimeZone();
EXPECT_EQ(timeZoneRes, timeZoneSet);
}
@@ -91,16 +91,13 @@ HWTEST_F(TimeServiceTest, SetTimeZone001, TestSize.Level0)
*/
HWTEST_F(TimeServiceTest, SetTimeZone002, TestSize.Level0)
{
struct timezone tz = {};
gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "Before set timezone, GMT offset in kernel : %{public}d", tz.tz_minuteswest);
time_t t;
(void)time(&t);
TIME_HILOGI(TIME_MODULE_CLIENT, "Time before: %{public}s", asctime(localtime(&t)));
std::string timeZoneSet("Asia/Ulaanbaatar");
bool result = TimeServiceClient::GetInstance()->SetTimeZone(timeZoneSet);
EXPECT_TRUE(result);
auto ret = gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "gettimeofday result : %{public}d", ret);
TIME_HILOGD(TIME_MODULE_CLIENT, "After set timezone, GMT offset minutes in kernel : %{public}d", tz.tz_minuteswest);
auto timeZoneRes = TimeServiceClient::GetInstance()->GetTimeZone();
EXPECT_EQ(timeZoneRes, timeZoneSet);
}
@@ -209,63 +206,6 @@ HWTEST_F(TimeServiceTest, GetTime008, TestSize.Level0)
EXPECT_TRUE(time2 >= time1);
}
/**
* @tc.name: CreateTimer01
* @tc.desc: Create system timer.
* @tc.type: FUNC
*/
HWTEST_F(TimeServiceTest, CreateTimer001, TestSize.Level0)
{
g_data1 = 0;
auto timerInfo = std::make_shared<TimerInfoTest>();
timerInfo->SetType(1);
timerInfo->SetRepeat(false);
timerInfo->SetInterval(0);
timerInfo->SetWantAgent(nullptr);
timerInfo->SetCallbackInfo(TimeOutCallback1);
auto timerId1 = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
EXPECT_TRUE(timerId1 > 0);
auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId1, 5);
std::this_thread::sleep_for(std::chrono::milliseconds(6000));
EXPECT_TRUE(ret);
EXPECT_TRUE(g_data1 == 1);
ret = TimeServiceClient::GetInstance()->StopTimer(timerId1);
EXPECT_TRUE(ret);
ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId1);
EXPECT_TRUE(ret);
}
/**
* @tc.name: CreateTimer02
* @tc.desc: Create system timer.
* @tc.type: FUNC
*/
HWTEST_F(TimeServiceTest, CreateTimer002, TestSize.Level0)
{
g_data1 = 0;
auto timerInfo = std::make_shared<TimerInfoTest>();
timerInfo->SetType(1);
timerInfo->SetRepeat(false);
timerInfo->SetInterval(0);
timerInfo->SetWantAgent(nullptr);
timerInfo->SetCallbackInfo(TimeOutCallback1);
auto timerId1 = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
EXPECT_TRUE(timerId1 > 0);
auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId1, 5000);
std::this_thread::sleep_for(std::chrono::milliseconds(5100));
EXPECT_TRUE(ret);
EXPECT_TRUE(g_data1 == 1);
ret = TimeServiceClient::GetInstance()->StopTimer(timerId1);
EXPECT_TRUE(ret);
ret = TimeServiceClient::GetInstance()->StartTimer(timerId1, 5000);
EXPECT_TRUE(ret);
EXPECT_TRUE(g_data1 == 1);
ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId1);
EXPECT_TRUE(ret);
}
/**
* @tc.name: CreateTimer03
* @tc.desc: Create system timer.
@@ -321,8 +261,9 @@ HWTEST_F(TimeServiceTest, CreateTimer005, TestSize.Level0)
timerInfo->SetCallbackInfo(TimeOutCallback1);
auto timerId1 = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
EXPECT_TRUE(timerId1 > 0);
auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId1, 2000);
auto BootTimeNano = system_clock::now().time_since_epoch().count();
auto BootTimeMilli = BootTimeNano / NANO_TO_MILESECOND;
auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId1, BootTimeMilli + 2000);
EXPECT_TRUE(ret);
ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId1);
EXPECT_TRUE(ret);
@@ -333,7 +274,7 @@ HWTEST_F(TimeServiceTest, CreateTimer005, TestSize.Level0)
}
/**
* @tc.name: CreateTimer06
* @tc.name: CreateTimer06.
* @tc.desc: Create system timer.
* @tc.type: FUNC
*/
@@ -347,7 +288,7 @@ HWTEST_F(TimeServiceTest, CreateTimer006, TestSize.Level0)
timerInfo->SetWantAgent(nullptr);
timerInfo->SetCallbackInfo(TimeOutCallback1);
struct timeval getTime;
struct timeval getTime {};
gettimeofday(&getTime, NULL);
int64_t current_time = (getTime.tv_sec + 100) * 1000 + getTime.tv_usec / 1000;
if (current_time < 0) {
+1 -1
View File
@@ -185,7 +185,7 @@ void TimerManager::SetHandler(uint64_t id,
}
auto nowElapsed = steady_clock::now();
auto nominalTrigger = ConvertToElapsed(milliseconds(triggerAtTime), type);
auto minTrigger = (IsSystemUid(uid)) ? nowElapsed + ZERO_FUTURITY : nowElapsed + MIN_FUTURITY;
auto minTrigger = (IsSystemUid(uid)) ? (nowElapsed + ZERO_FUTURITY) : (nowElapsed + MIN_FUTURITY);
auto triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
steady_clock::time_point maxElapsed;
+2 -3
View File
@@ -23,21 +23,20 @@ config("utils_config") {
}
ohos_source_set("time_utils") {
configs = [ ":utils_config" ]
sources = [
"mock/src/mock_permission.cpp",
"native/src/time_file_utils.cpp",
"native/src/time_permission.cpp",
]
public_configs = [ ":utils_config" ]
deps = [
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk:native_appdatafwk",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_preferences:native_preferences",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//utils/native/base:utils",
+1 -1
View File
@@ -27,7 +27,7 @@
namespace OHOS {
namespace MiscServices {
class TimePermission {
class TimePermission : public std::enable_shared_from_this<TimePermission> {
DECLARE_DELAYED_SINGLETON(TimePermission)
public:
bool CheckSelfPermission(const std::string permName);