Bumping manifests a=b2g-bump
[gecko.git] / hal / fallback / FallbackAlarm.cpp
blobf7e08d0c37e129129f6e84ab271f8f52ce7ed083
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "Hal.h"
7 #include <algorithm>
9 #include "mozilla/ClearOnShutdown.h"
10 #include "mozilla/StaticPtr.h"
11 #include "nsComponentManagerUtils.h"
12 #include "nsITimer.h"
13 #include "nsThreadUtils.h"
15 namespace mozilla {
16 namespace hal_impl {
18 static void
19 TimerCallbackFunc(nsITimer *aTimer, void *aClosure)
21 hal::NotifyAlarmFired();
24 static StaticRefPtr<nsITimer> sTimer;
26 bool
27 EnableAlarm()
29 static bool initialized = false;
30 if (!initialized) {
31 initialized = true;
32 ClearOnShutdown(&sTimer);
35 nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1");
36 sTimer = timer;
37 MOZ_ASSERT(sTimer);
38 return true;
41 void
42 DisableAlarm()
45 * DisableAlarm() may be called after sTimer has been set to null by
46 * ClearOnShutdown().
48 if (sTimer) {
49 sTimer->Cancel();
53 bool
54 SetAlarm(int32_t aSeconds, int32_t aNanoseconds)
56 if (!sTimer) {
57 HAL_LOG(("We should have enabled the alarm"));
58 MOZ_ASSERT(false);
59 return false;
62 // Do the math to convert aSeconds and aNanoseconds into milliseconds since
63 // the epoch.
64 int64_t milliseconds = static_cast<int64_t>(aSeconds) * 1000 +
65 static_cast<int64_t>(aNanoseconds) / 1000000;
67 // nsITimer expects relative milliseconds.
68 int64_t relMilliseconds = milliseconds - PR_Now() / 1000;
70 // If the alarm time is in the past relative to PR_Now(),
71 // we choose to immediately fire the alarm. Passing 0 means nsITimer will
72 // queue a timeout event immediately.
73 sTimer->InitWithFuncCallback(TimerCallbackFunc, nullptr,
74 clamped<int64_t>(relMilliseconds, 0, INT32_MAX),
75 nsITimer::TYPE_ONE_SHOT);
76 return true;
79 } // hal_impl
80 } // namespace mozilla