3 * Copyright 2017 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/lib/iomgr/port.h"
23 #include <grpc/support/alloc.h>
24 #include <grpc/support/log.h>
26 #include "src/core/lib/debug/trace.h"
27 #include "src/core/lib/iomgr/iomgr_custom.h"
28 #include "src/core/lib/iomgr/timer.h"
29 #include "src/core/lib/iomgr/timer_custom.h"
31 static grpc_custom_timer_vtable* custom_timer_impl;
33 void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error) {
34 GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
35 grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
36 grpc_core::ExecCtx exec_ctx;
37 grpc_timer* timer = t->original;
38 GPR_ASSERT(timer->pending);
40 GRPC_CLOSURE_SCHED(timer->closure, GRPC_ERROR_NONE);
41 custom_timer_impl->stop(t);
45 static void timer_init(grpc_timer* timer, grpc_millis deadline,
46 grpc_closure* closure) {
48 GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
49 grpc_millis now = grpc_core::ExecCtx::Get()->Now();
50 if (deadline <= grpc_core::ExecCtx::Get()->Now()) {
51 GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_NONE);
52 timer->pending = false;
55 timeout = deadline - now;
57 timer->pending = true;
58 timer->closure = closure;
59 grpc_custom_timer* timer_wrapper =
60 (grpc_custom_timer*)gpr_malloc(sizeof(grpc_custom_timer));
61 timer_wrapper->timeout_ms = timeout;
62 timer->custom_timer = (void*)timer_wrapper;
63 timer_wrapper->original = timer;
64 custom_timer_impl->start(timer_wrapper);
67 static void timer_cancel(grpc_timer* timer) {
68 GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
69 grpc_custom_timer* tw = (grpc_custom_timer*)timer->custom_timer;
72 GRPC_CLOSURE_SCHED(timer->closure, GRPC_ERROR_CANCELLED);
73 custom_timer_impl->stop(tw);
78 static grpc_timer_check_result timer_check(grpc_millis* next) {
79 return GRPC_TIMERS_NOT_CHECKED;
82 static void timer_list_init() {}
83 static void timer_list_shutdown() {}
85 static void timer_consume_kick(void) {}
87 static grpc_timer_vtable custom_timer_vtable = {
88 timer_init, timer_cancel, timer_check,
89 timer_list_init, timer_list_shutdown, timer_consume_kick};
91 void grpc_custom_timer_init(grpc_custom_timer_vtable* impl) {
92 custom_timer_impl = impl;
93 grpc_set_timer_impl(&custom_timer_vtable);