Bug 1404198: Part 2c - Switch to NS_NewTimer* in necko. r=njn
authorKris Maglione <maglione.k@gmail.com>
Sun, 15 Oct 2017 23:12:02 -0700
changeset 386547 fa53cb4191939e1d66446f5e45175e0079197082
parent 386546 e1f1ce79ba5cd667c098fe188853a3dbbba2c15e
child 386548 e7c3876d6d2f31f137dd9d62c870ed6320963770
push id32695
push userarchaeopteryx@coole-files.de
push dateTue, 17 Oct 2017 09:45:44 +0000
treeherdermozilla-central@0d9c6250f99d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersnjn
bugs1404198
milestone58.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1404198: Part 2c - Switch to NS_NewTimer* in necko. r=njn MozReview-Commit-ID: 3YyyaBAEjHc
netwerk/base/CaptivePortalService.cpp
netwerk/base/Dashboard.cpp
netwerk/base/EventTokenBucket.cpp
netwerk/base/Predictor.cpp
netwerk/base/ProxyAutoConfig.cpp
netwerk/base/ThrottleQueue.cpp
netwerk/base/Tickler.cpp
netwerk/base/nsIncrementalDownload.cpp
netwerk/base/nsSocketTransportService2.cpp
netwerk/cache/nsCacheService.cpp
netwerk/cache/nsDeleteDir.cpp
netwerk/cache/nsDiskCacheMap.cpp
netwerk/cache2/CacheFileIOManager.cpp
netwerk/cache2/CacheIndex.cpp
netwerk/cache2/CacheStorageService.cpp
netwerk/protocol/ftp/nsFtpProtocolHandler.cpp
netwerk/protocol/http/HSTSPrimerListener.cpp
netwerk/protocol/http/TunnelUtils.cpp
netwerk/protocol/http/nsHttpChannel.cpp
netwerk/protocol/http/nsHttpConnection.cpp
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/websocket/WebSocketChannel.cpp
netwerk/test/TestUDPSocket.cpp
--- a/netwerk/base/CaptivePortalService.cpp
+++ b/netwerk/base/CaptivePortalService.cpp
@@ -88,17 +88,17 @@ CaptivePortalService::RearmTimer()
   // If we have successfully determined the state, and we have never detected
   // a captive portal, we don't need to keep polling, but will rely on events
   // to trigger detection.
   if (mState == NOT_CAPTIVE) {
     return NS_OK;
   }
 
   if (!mTimer) {
-    mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+    mTimer = NS_NewTimer();
   }
 
   if (mTimer && mDelay > 0) {
     LOG(("CaptivePortalService - Reloading timer with delay %u\n", mDelay));
     return mTimer->InitWithCallback(this, mDelay, nsITimer::TYPE_ONE_SHOT);
   }
 
   return NS_OK;
--- a/netwerk/base/Dashboard.cpp
+++ b/netwerk/base/Dashboard.cpp
@@ -238,17 +238,17 @@ ConnectionData::Notify(nsITimer *aTimer)
 
     return NS_OK;
 }
 
 void
 ConnectionData::StartTimer(uint32_t aTimeout)
 {
     if (!mTimer) {
-        mTimer = do_CreateInstance("@mozilla.org/timer;1");
+        mTimer = NS_NewTimer();
     }
 
     mTimer->InitWithCallback(this, aTimeout * 1000,
         nsITimer::TYPE_ONE_SHOT);
 }
 
 void
 ConnectionData::StopTimer()
--- a/netwerk/base/EventTokenBucket.cpp
+++ b/netwerk/base/EventTokenBucket.cpp
@@ -95,19 +95,17 @@ EventTokenBucket::EventTokenBucket(uint3
   MOZ_ASSERT(NS_IsMainThread());
 
   nsresult rv;
   nsCOMPtr<nsIEventTarget> sts;
   nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
   if (NS_SUCCEEDED(rv))
     sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
   if (NS_SUCCEEDED(rv))
-    mTimer = do_CreateInstance("@mozilla.org/timer;1");
-  if (mTimer)
-    mTimer->SetTarget(sts);
+    mTimer = NS_NewTimer(sts);
   SetRate(eventsPerSecond, burstSize);
 }
 
 EventTokenBucket::~EventTokenBucket()
 {
   SOCKET_LOG(("EventTokenBucket::dtor %p events=%zu\n",
               this, mEvents.GetSize()));
 
@@ -425,17 +423,17 @@ EventTokenBucket::WantNormalTimers()
     static const TimeDuration fiveSeconds = TimeDuration::FromSeconds(5);
 
     if (elapsed >= fiveSeconds) {
       NormalTimers();
       return;
     }
 
     if (!mFineGrainResetTimer)
-      mFineGrainResetTimer = do_CreateInstance("@mozilla.org/timer;1");
+      mFineGrainResetTimer = NS_NewTimer();
 
     // if we can't delay the reset, just do it now
     if (!mFineGrainResetTimer) {
       NormalTimers();
       return;
     }
 
     // pad the callback out 100ms to avoid having to round trip this again if the
--- a/netwerk/base/Predictor.cpp
+++ b/netwerk/base/Predictor.cpp
@@ -446,18 +446,18 @@ Predictor::InstallObserver()
   Preferences::AddBoolVarCache(&mCleanedUp, PREDICTOR_CLEANED_UP_PREF, false);
 
   Preferences::AddUintVarCache(&mMaxURILength, PREDICTOR_MAX_URI_LENGTH_PREF,
                                PREDICTOR_MAX_URI_LENGTH_DEFAULT);
 
   Preferences::AddBoolVarCache(&mDoingTests, PREDICTOR_DOING_TESTS_PREF, false);
 
   if (!mCleanedUp) {
-    mCleanupTimer = do_CreateInstance("@mozilla.org/timer;1");
-    mCleanupTimer->Init(this, 60 * 1000, nsITimer::TYPE_ONE_SHOT);
+    NS_NewTimerWithObserver(getter_AddRefs(mCleanupTimer),
+                            this, 60 * 1000, nsITimer::TYPE_ONE_SHOT);
   }
 
   return rv;
 }
 
 void
 Predictor::RemoveObserver()
 {
--- a/netwerk/base/ProxyAutoConfig.cpp
+++ b/netwerk/base/ProxyAutoConfig.cpp
@@ -435,17 +435,17 @@ ProxyAutoConfig::ResolveAddress(const ns
                                         helper,
                                         GetCurrentThreadEventTarget(),
                                         attrs,
                                         getter_AddRefs(helper->mRequest))))
     return false;
 
   if (aTimeout && helper->mRequest) {
     if (!mTimer)
-      mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+      mTimer = NS_NewTimer();
     if (mTimer) {
       mTimer->SetTarget(mMainThreadEventTarget);
       mTimer->InitWithCallback(helper, aTimeout, nsITimer::TYPE_ONE_SHOT);
       helper->mTimer = mTimer;
     }
   }
 
   // Spin the event loop of the pac thread until lookup is complete.
--- a/netwerk/base/ThrottleQueue.cpp
+++ b/netwerk/base/ThrottleQueue.cpp
@@ -244,19 +244,17 @@ ThrottleQueue::ThrottleQueue()
   , mTimerArmed(false)
 {
   nsresult rv;
   nsCOMPtr<nsIEventTarget> sts;
   nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
   if (NS_SUCCEEDED(rv))
     sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
   if (NS_SUCCEEDED(rv))
-    mTimer = do_CreateInstance("@mozilla.org/timer;1");
-  if (mTimer)
-    mTimer->SetTarget(sts);
+    mTimer = NS_NewTimer(sts);
 }
 
 ThrottleQueue::~ThrottleQueue()
 {
   if (mTimer && mTimerArmed) {
     mTimer->Cancel();
   }
   mTimer = nullptr;
--- a/netwerk/base/Tickler.cpp
+++ b/netwerk/base/Tickler.cpp
@@ -75,23 +75,19 @@ Tickler::Init()
   opt.value.ip_ttl = 1;
   PR_SetSocketOption(mFD, &opt);
 
   nsresult rv = NS_NewNamedThread("wifi tickler",
                                   getter_AddRefs(mThread));
   if (NS_FAILED(rv))
     return rv;
 
-  nsCOMPtr<nsITimer> tmpTimer(do_CreateInstance(NS_TIMER_CONTRACTID, &rv));
-  if (NS_FAILED(rv))
-    return rv;
-
-  rv = tmpTimer->SetTarget(mThread);
-  if (NS_FAILED(rv))
-    return rv;
+  nsCOMPtr<nsITimer> tmpTimer = NS_NewTimer(mThread);
+  if (!tmpTimer)
+    return NS_ERROR_OUT_OF_MEMORY;
 
   mTimer.swap(tmpTimer);
 
   mAddr.inet.family = PR_AF_INET;
   mAddr.inet.port = PR_htons (4886);
   mAddr.inet.ip = 0;
 
   return NS_OK;
--- a/netwerk/base/nsIncrementalDownload.cpp
+++ b/netwerk/base/nsIncrementalDownload.cpp
@@ -221,22 +221,19 @@ nsIncrementalDownload::CallOnStopRequest
   mObserver->OnStopRequest(this, mObserverContext, mStatus);
   mObserver = nullptr;
   mObserverContext = nullptr;
 }
 
 nsresult
 nsIncrementalDownload::StartTimer(int32_t interval)
 {
-  nsresult rv;
-  mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-  if (NS_FAILED(rv))
-    return rv;
-
-  return mTimer->Init(this, interval * 1000, nsITimer::TYPE_ONE_SHOT);
+  return NS_NewTimerWithObserver(getter_AddRefs(mTimer),
+                                 this, interval * 1000,
+                                 nsITimer::TYPE_ONE_SHOT);
 }
 
 nsresult
 nsIncrementalDownload::ProcessTimeout()
 {
   NS_ASSERTION(!mChannel, "how can we have a channel?");
 
   // Handle existing error conditions
--- a/netwerk/base/nsSocketTransportService2.cpp
+++ b/netwerk/base/nsSocketTransportService2.cpp
@@ -1428,20 +1428,18 @@ nsSocketTransportService::Observe(nsISup
     } else if (!strcmp(topic, NS_WIDGET_SLEEP_OBSERVER_TOPIC)) {
         mSleepPhase = true;
         if (mAfterWakeUpTimer) {
             mAfterWakeUpTimer->Cancel();
             mAfterWakeUpTimer = nullptr;
         }
     } else if (!strcmp(topic, NS_WIDGET_WAKE_OBSERVER_TOPIC)) {
         if (mSleepPhase && !mAfterWakeUpTimer) {
-            mAfterWakeUpTimer = do_CreateInstance("@mozilla.org/timer;1");
-            if (mAfterWakeUpTimer) {
-                mAfterWakeUpTimer->Init(this, 2000, nsITimer::TYPE_ONE_SHOT);
-            }
+            NS_NewTimerWithObserver(getter_AddRefs(mAfterWakeUpTimer),
+                                    this, 2000, nsITimer::TYPE_ONE_SHOT);
         }
     } else if (!strcmp(topic, "xpcom-shutdown-threads")) {
         ShutdownThread();
     }
 
     return NS_OK;
 }
 
@@ -1660,19 +1658,19 @@ nsSocketTransportService::StartPollWatch
                                                    [self] {
          MutexAutoLock lock(self->mLock);
 
          // Poll can hang sometimes. If we are in shutdown, we are going to start a
          // watchdog. If we do not exit poll within REPAIR_POLLABLE_EVENT_TIME
          // signal a pollable event again.
          MOZ_ASSERT(gIOService->IsNetTearingDown());
          if (self->mPolling && !self->mPollRepairTimer) {
-             self->mPollRepairTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-             self->mPollRepairTimer->Init(self, REPAIR_POLLABLE_EVENT_TIME,
-                                          nsITimer::TYPE_REPEATING_SLACK);
+             NS_NewTimerWithObserver(getter_AddRefs(self->mPollRepairTimer),
+                                     self, REPAIR_POLLABLE_EVENT_TIME,
+                                     nsITimer::TYPE_REPEATING_SLACK);
          }
     }));
 }
 
 void
 nsSocketTransportService::DoPollRepair()
 {
     MutexAutoLock lock(mLock);
--- a/netwerk/cache/nsCacheService.cpp
+++ b/netwerk/cache/nsCacheService.cpp
@@ -1627,27 +1627,22 @@ nsCacheService::CreateDiskDevice()
         return rv;
     }
 
     NS_ASSERTION(!mSmartSizeTimer, "Smartsize timer was already fired!");
 
     // Disk device is usually created during the startup. Delay smart size
     // calculation to avoid possible massive IO caused by eviction of entries
     // in case the new smart size is smaller than current cache usage.
-    mSmartSizeTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if (NS_SUCCEEDED(rv)) {
-        rv = mSmartSizeTimer->InitWithCallback(new nsSetDiskSmartSizeCallback(),
-                                               1000*60*3,
-                                               nsITimer::TYPE_ONE_SHOT);
-        if (NS_FAILED(rv)) {
-            NS_WARNING("Failed to post smart size timer");
-            mSmartSizeTimer = nullptr;
-        }
-    } else {
-        NS_WARNING("Can't create smart size timer");
+    rv = NS_NewTimerWithCallback(getter_AddRefs(mSmartSizeTimer),
+                                 new nsSetDiskSmartSizeCallback(),
+                                 1000*60*3,
+                                 nsITimer::TYPE_ONE_SHOT);
+    if (NS_FAILED(rv)) {
+        NS_WARNING("Failed to post smart size timer");
     }
     // Ignore state of the timer and return success since the purpose of the
     // method (create the disk-device) has been fulfilled
 
     return NS_OK;
 }
 
 // Runnable sent from cache thread to main thread
--- a/netwerk/cache/nsDeleteDir.cpp
+++ b/netwerk/cache/nsDeleteDir.cpp
@@ -374,35 +374,30 @@ nsDeleteDir::RemoveOldTrashes(nsIFile *c
   return NS_OK;
 }
 
 nsresult
 nsDeleteDir::PostTimer(void *arg, uint32_t delay)
 {
   nsresult rv;
 
-  nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  if (NS_FAILED(rv))
-    return NS_ERROR_UNEXPECTED;
-
   MutexAutoLock lock(mLock);
 
   rv = InitThread();
   if (NS_FAILED(rv))
     return rv;
 
-  rv = timer->SetTarget(mThread);
-  if (NS_FAILED(rv))
-    return rv;
-
-  rv = timer->InitWithNamedFuncCallback(TimerCallback,
-                                        arg,
-                                        delay,
-                                        nsITimer::TYPE_ONE_SHOT,
-                                        "nsDeleteDir::PostTimer");
+  nsCOMPtr<nsITimer> timer;
+  rv = NS_NewTimerWithFuncCallback(getter_AddRefs(timer),
+                                   TimerCallback,
+                                   arg,
+                                   delay,
+                                   nsITimer::TYPE_ONE_SHOT,
+                                   "nsDeleteDir::PostTimer",
+                                   mThread);
   if (NS_FAILED(rv))
     return rv;
 
   mTimers.AppendObject(timer);
   return NS_OK;
 }
 
 nsresult
--- a/netwerk/cache/nsDiskCacheMap.cpp
+++ b/netwerk/cache/nsDiskCacheMap.cpp
@@ -1274,21 +1274,18 @@ nsDiskCacheMap::InitCacheClean(nsIFile *
         int32_t bytesRead = PR_Read(mCleanFD, &clean, 1);
         if (bytesRead != 1) {
             NS_WARNING("Could not read _CACHE_CLEAN_ file contents");
         }
     }
 
     // Create a timer that will be used to validate the cache
     // as long as an activity threshold was met
-    mCleanCacheTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if (NS_SUCCEEDED(rv)) {
-        mCleanCacheTimer->SetTarget(nsCacheService::GlobalInstance()->mCacheIOThread);
-        rv = ResetCacheTimer();
-    }
+    mCleanCacheTimer = NS_NewTimer(nsCacheService::GlobalInstance()->mCacheIOThread);
+    rv = mCleanCacheTimer ? ResetCacheTimer() : NS_ERROR_OUT_OF_MEMORY;
 
     if (NS_FAILED(rv)) {
         NS_WARNING("Could not create cache clean timer");
         mCleanCacheTimer = nullptr;
         *corruptInfo = nsDiskCache::kCacheCleanTimerError;
         return rv;
     }
 
--- a/netwerk/cache2/CacheFileIOManager.cpp
+++ b/netwerk/cache2/CacheFileIOManager.cpp
@@ -1519,21 +1519,19 @@ CacheFileIOManager::ScheduleMetadataWrit
 nsresult
 CacheFileIOManager::ScheduleMetadataWriteInternal(CacheFile * aFile)
 {
   MOZ_ASSERT(IsOnIOThreadOrCeased());
 
   nsresult rv;
 
   if (!mMetadataWritesTimer) {
-    mMetadataWritesTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = mMetadataWritesTimer->InitWithCallback(
-      this, kMetadataWriteDelay, nsITimer::TYPE_ONE_SHOT);
+    rv = NS_NewTimerWithCallback(getter_AddRefs(mMetadataWritesTimer),
+                                 this, kMetadataWriteDelay,
+                                 nsITimer::TYPE_ONE_SHOT);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   if (mScheduledMetadataWrites.IndexOf(aFile) !=
       mScheduledMetadataWrites.NoIndex) {
     return NS_OK;
   }
 
@@ -3434,35 +3432,27 @@ CacheFileIOManager::StartRemovingTrash()
   if (mRemovingTrashDirs) {
     LOG(("CacheFileIOManager::StartRemovingTrash() - Trash removing in "
          "progress."));
     return NS_OK;
   }
 
   uint32_t elapsed = (TimeStamp::NowLoRes() - mStartTime).ToMilliseconds();
   if (elapsed < kRemoveTrashStartDelay) {
-    nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-
     nsCOMPtr<nsIEventTarget> ioTarget = IOTarget();
     MOZ_ASSERT(ioTarget);
 
-    rv = timer->SetTarget(ioTarget);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = timer->InitWithNamedFuncCallback(
+    return NS_NewTimerWithFuncCallback(
+      getter_AddRefs(mTrashTimer),
       CacheFileIOManager::OnTrashTimer,
       nullptr,
       kRemoveTrashStartDelay - elapsed,
       nsITimer::TYPE_ONE_SHOT,
-      "net::CacheFileIOManager::StartRemovingTrash");
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    mTrashTimer.swap(timer);
-    return NS_OK;
+      "net::CacheFileIOManager::StartRemovingTrash",
+      ioTarget);
   }
 
   nsCOMPtr<nsIRunnable> ev;
   ev = NewRunnableMethod("net::CacheFileIOManager::RemoveTrashInternal",
                          this,
                          &CacheFileIOManager::RemoveTrashInternal);
 
   rv = mIOThread->Dispatch(ev, CacheIOThread::EVICT);
--- a/netwerk/cache2/CacheIndex.cpp
+++ b/netwerk/cache2/CacheIndex.cpp
@@ -2646,36 +2646,26 @@ CacheIndex::DelayedUpdateLocked()
 
 nsresult
 CacheIndex::ScheduleUpdateTimer(uint32_t aDelay)
 {
   LOG(("CacheIndex::ScheduleUpdateTimer() [delay=%u]", aDelay));
 
   MOZ_ASSERT(!mUpdateTimer);
 
-  nsresult rv;
-
-  nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   nsCOMPtr<nsIEventTarget> ioTarget = CacheFileIOManager::IOTarget();
   MOZ_ASSERT(ioTarget);
 
-  rv = timer->SetTarget(ioTarget);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = timer->InitWithNamedFuncCallback(CacheIndex::DelayedUpdate,
-                                        nullptr,
-                                        aDelay,
-                                        nsITimer::TYPE_ONE_SHOT,
-                                        "net::CacheIndex::ScheduleUpdateTimer");
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mUpdateTimer.swap(timer);
-  return NS_OK;
+  return NS_NewTimerWithFuncCallback(getter_AddRefs(mUpdateTimer),
+                                     CacheIndex::DelayedUpdate,
+                                     nullptr,
+                                     aDelay,
+                                     nsITimer::TYPE_ONE_SHOT,
+                                     "net::CacheIndex::ScheduleUpdateTimer",
+                                     ioTarget);
 }
 
 nsresult
 CacheIndex::SetupDirectoryEnumerator()
 {
   MOZ_ASSERT(!NS_IsMainThread());
   MOZ_ASSERT(!mDirEnumerator);
 
--- a/netwerk/cache2/CacheStorageService.cpp
+++ b/netwerk/cache2/CacheStorageService.cpp
@@ -1230,17 +1230,17 @@ CacheStorageService::SchedulePurgeOverMe
     return;
   }
 
   if (mPurgeTimer) {
     LOG(("  timer already up"));
     return;
   }
 
-  mPurgeTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mPurgeTimer = NS_NewTimer();
   if (mPurgeTimer) {
     nsresult rv;
     rv = mPurgeTimer->InitWithCallback(this, 1000, nsITimer::TYPE_ONE_SHOT);
     LOG(("  timer init rv=0x%08" PRIx32, static_cast<uint32_t>(rv)));
   }
 }
 
 NS_IMETHODIMP
--- a/netwerk/protocol/ftp/nsFtpProtocolHandler.cpp
+++ b/netwerk/protocol/ftp/nsFtpProtocolHandler.cpp
@@ -304,30 +304,27 @@ nsFtpProtocolHandler::InsertConnection(n
     if (aConn->mSessionId != mSessionId)
         return NS_ERROR_FAILURE;
 
     nsAutoCString spec;
     aKey->GetPrePath(spec);
 
     LOG(("FTP:inserting connection for %s\n", spec.get()));
 
-    nsresult rv;
-    nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if (NS_FAILED(rv)) return rv;
-
     timerStruct* ts = new timerStruct();
     if (!ts)
         return NS_ERROR_OUT_OF_MEMORY;
 
-    rv = timer->InitWithNamedFuncCallback(
-      nsFtpProtocolHandler::Timeout,
-      ts,
-      mIdleTimeout * 1000,
-      nsITimer::TYPE_REPEATING_SLACK,
-      "nsFtpProtocolHandler::InsertConnection");
+    nsCOMPtr<nsITimer> timer;
+    nsresult rv = NS_NewTimerWithFuncCallback(getter_AddRefs(timer),
+                                              nsFtpProtocolHandler::Timeout,
+                                              ts,
+                                              mIdleTimeout * 1000,
+                                              nsITimer::TYPE_REPEATING_SLACK,
+                                              "nsFtpProtocolHandler::InsertConnection");
     if (NS_FAILED(rv)) {
         delete ts;
         return rv;
     }
 
     ts->key = ToNewCString(spec);
     if (!ts->key) {
         delete ts;
--- a/netwerk/protocol/http/HSTSPrimerListener.cpp
+++ b/netwerk/protocol/http/HSTSPrimerListener.cpp
@@ -370,20 +370,19 @@ HSTSPrimingListener::StartHSTSPriming(ns
 
   // Set up listener which will start the original channel
   HSTSPrimingListener* listener = new HSTSPrimingListener(aCallback);
   // Start priming
   rv = primingChannel->AsyncOpen2(listener);
   NS_ENSURE_SUCCESS(rv, rv);
   listener->mPrimingChannel.swap(primingChannel);
 
-  nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
-  NS_ENSURE_STATE(timer);
-
-  rv = timer->InitWithCallback(listener,
+  nsCOMPtr<nsITimer> timer;
+  rv = NS_NewTimerWithCallback(getter_AddRefs(timer),
+                               listener,
                                sHSTSPrimingTimeout,
                                nsITimer::TYPE_ONE_SHOT);
   if (NS_FAILED(rv)) {
     NS_ERROR("HSTS Priming failed to initialize channel cancellation timer");
   }
 
   listener->mHSTSPrimingTimer.swap(timer);
 
--- a/netwerk/protocol/http/TunnelUtils.cpp
+++ b/netwerk/protocol/http/TunnelUtils.cpp
@@ -419,17 +419,17 @@ TLSFilterTransaction::NudgeTunnel(NudgeT
     delay = 6;
   } else if (counter < 34) { // up to 499 ms at 17ms
     delay = 17;
   } else { // after that at 51ms (3 old windows ticks)
     delay = 51;
   }
 
   if(!mTimer) {
-    mTimer = do_CreateInstance("@mozilla.org/timer;1");
+    mTimer = NS_NewTimer();
   }
 
   mNudgeCallback = aCallback;
   if (!mTimer ||
       NS_FAILED(mTimer->InitWithCallback(this, delay, nsITimer::TYPE_ONE_SHOT))) {
     return StartTimerCallback();
   }
 
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -3928,19 +3928,20 @@ nsHttpChannel::OpenCacheEntry(bool isHtt
         mCacheOpenFunc = [openURI, extension, cacheEntryOpenFlags, cacheStorage] (nsHttpChannel* self) -> void {
             MOZ_ASSERT(NS_IsMainThread(), "Should be called on the main thread");
             if (self->mNetworkTriggered) {
                 self->mRaceCacheWithNetwork = true;
             }
             cacheStorage->AsyncOpenURI(openURI, extension, cacheEntryOpenFlags, self);
         };
 
-        mCacheOpenTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
         // calls nsHttpChannel::Notify after `mCacheOpenDelay` milliseconds
-        mCacheOpenTimer->InitWithCallback(this, mCacheOpenDelay, nsITimer::TYPE_ONE_SHOT);
+        NS_NewTimerWithCallback(getter_AddRefs(mCacheOpenTimer),
+                                this, mCacheOpenDelay,
+                                nsITimer::TYPE_ONE_SHOT);
 
     }
     NS_ENSURE_SUCCESS(rv, rv);
 
     waitFlags.Keep(WAIT_FOR_CACHE_ENTRY);
 
 bypassCacheEntryOpen:
     if (!mApplicationCacheForWrite)
@@ -9262,17 +9263,17 @@ nsHttpChannel::TriggerNetworkWithDelay(u
         // cause performance regression in tp6 tests, see bug 1398847.
         return NS_DispatchToMainThread(
             NewRunnableMethod("net::nsHttpChannel::TriggerNetworkWithDelay",
                               this, &nsHttpChannel::TriggerNetwork),
             NS_DISPATCH_NORMAL);
     }
 
     if (!mNetworkTriggerTimer) {
-        mNetworkTriggerTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+        mNetworkTriggerTimer = NS_NewTimer();
     }
     mNetworkTriggerTimer->InitWithCallback(this, aDelay, nsITimer::TYPE_ONE_SHOT);
     return NS_OK;
 }
 
 nsresult
 nsHttpChannel::TriggerNetwork()
 {
--- a/netwerk/protocol/http/nsHttpConnection.cpp
+++ b/netwerk/protocol/http/nsHttpConnection.cpp
@@ -1542,23 +1542,23 @@ nsHttpConnection::MaybeForceSendIO()
     // tick interval (kForceDelay) as a backup for those circumstances.
     static const uint32_t kForceDelay = 17; //ms
 
     if (mForceSendPending) {
         return NS_OK;
     }
     MOZ_ASSERT(!mForceSendTimer);
     mForceSendPending = true;
-    mForceSendTimer = do_CreateInstance("@mozilla.org/timer;1");
-    return mForceSendTimer->InitWithNamedFuncCallback(
-      nsHttpConnection::ForceSendIO,
-      this,
-      kForceDelay,
-      nsITimer::TYPE_ONE_SHOT,
-      "net::nsHttpConnection::MaybeForceSendIO");
+    return NS_NewTimerWithFuncCallback(
+        getter_AddRefs(mForceSendTimer),
+        nsHttpConnection::ForceSendIO,
+        this,
+        kForceDelay,
+        nsITimer::TYPE_ONE_SHOT,
+        "net::nsHttpConnection::MaybeForceSendIO");
 }
 
 // trigger an asynchronous read
 nsresult
 nsHttpConnection::ForceRecv()
 {
     LOG(("nsHttpConnection::ForceRecv [this=%p]\n", this));
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
@@ -2079,17 +2079,17 @@ nsHttpConnection::StartShortLivedTCPKeep
     }
     if (NS_FAILED(rv)) {
         return rv;
     }
 
     // Start a timer to move to long-lived keepalive config.
     if(!mTCPKeepaliveTransitionTimer) {
         mTCPKeepaliveTransitionTimer =
-            do_CreateInstance("@mozilla.org/timer;1");
+            NS_NewTimer();
     }
 
     if (mTCPKeepaliveTransitionTimer) {
         int32_t time = gHttpHandler->GetTCPKeepaliveShortLivedTime();
 
         // Adjust |time| to ensure a full set of keepalive probes can be sent
         // at the end of the short-lived phase.
         if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) {
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -300,17 +300,17 @@ nsHttpConnectionMgr::PostEvent(nsConnEve
 }
 
 void
 nsHttpConnectionMgr::PruneDeadConnectionsAfter(uint32_t timeInSeconds)
 {
     LOG(("nsHttpConnectionMgr::PruneDeadConnectionsAfter\n"));
 
     if(!mTimer)
-        mTimer = do_CreateInstance("@mozilla.org/timer;1");
+        mTimer = NS_NewTimer();
 
     // failure to create a timer is not a fatal error, but idle connections
     // will not be cleaned up until we try to use them.
     if (mTimer) {
         mTimeOfNextWakeUp = timeInSeconds + NowInSeconds();
         mTimer->Init(this, timeInSeconds*1000, nsITimer::TYPE_ONE_SHOT);
     } else {
         NS_WARNING("failed to create: timer for pruning the dead connections!");
@@ -2641,17 +2641,17 @@ nsHttpConnectionMgr::OnMsgVerifyTraffic(
         // Iterate the idle connections and unmark them for traffic checks.
         for (uint32_t index = 0; index < ent->mIdleConns.Length(); ++index) {
             ent->mIdleConns[index]->CheckForTraffic(false);
         }
     }
 
     // If the timer is already there. we just re-init it
     if(!mTrafficTimer) {
-        mTrafficTimer = do_CreateInstance("@mozilla.org/timer;1");
+        mTrafficTimer = NS_NewTimer();
     }
 
     // failure to create a timer is not a fatal error, but dead
     // connections will not be cleaned up as nicely
     if (mTrafficTimer) {
         // Give active connections time to get more traffic before killing
         // them off. Default: 5000 milliseconds
         mTrafficTimer->Init(this, gHttpHandler->NetworkChangedTimeout(),
@@ -2877,17 +2877,17 @@ nsHttpConnectionMgr::ActivateTimeoutTick
         if (mTimeoutTickNext > 1) {
             mTimeoutTickNext = 1;
             mTimeoutTick->SetDelay(1000);
         }
         return;
     }
 
     if (!mTimeoutTick) {
-        mTimeoutTick = do_CreateInstance(NS_TIMER_CONTRACTID);
+        mTimeoutTick = NS_NewTimer();
         if (!mTimeoutTick) {
             NS_WARNING("failed to create timer for http timeout management");
             return;
         }
         mTimeoutTick->SetTarget(mSocketThreadTarget);
     }
 
     MOZ_ASSERT(!mTimeoutTickArmed, "timer tick armed");
@@ -3273,17 +3273,17 @@ nsHttpConnectionMgr::EnsureThrottleTicke
     CancelDelayedResumeBackgroundThrottledTransactions();
 
     if (mThrottleTicker) {
         return;
     }
 
     MOZ_ASSERT(!mThrottlingInhibitsReading);
 
-    mThrottleTicker = do_CreateInstance("@mozilla.org/timer;1");
+    mThrottleTicker = NS_NewTimer();
     if (mThrottleTicker) {
         mThrottleTicker->Init(this, mThrottleSuspendFor, nsITimer::TYPE_ONE_SHOT);
         mThrottlingInhibitsReading = true;
     }
 
     LogActiveTransactions('^');
 }
 
@@ -3344,23 +3344,19 @@ nsHttpConnectionMgr::ThrottlerTick()
 
 void
 nsHttpConnectionMgr::DelayedResumeBackgroundThrottledTransactions()
 {
     if (mDelayedResumeReadTimer) {
         return;
     }
 
-    mDelayedResumeReadTimer = do_CreateInstance("@mozilla.org/timer;1");
-    if (!mDelayedResumeReadTimer) {
-        return;
-    }
-
     LOG(("nsHttpConnectionMgr::DelayedResumeBackgroundThrottledTransactions"));
-    mDelayedResumeReadTimer->Init(this, mThrottleResumeIn, nsITimer::TYPE_ONE_SHOT);
+    NS_NewTimerWithObserver(getter_AddRefs(mDelayedResumeReadTimer),
+                            this, mThrottleResumeIn, nsITimer::TYPE_ONE_SHOT);
 }
 
 void
 nsHttpConnectionMgr::CancelDelayedResumeBackgroundThrottledTransactions()
 {
     if (!mDelayedResumeReadTimer) {
         return;
     }
@@ -4009,22 +4005,19 @@ nsHttpConnectionMgr::nsHalfOpenSocket::S
         (timeout && !mSpeculative)) {
         // Setup the timer that will establish a backup socket
         // if we do not get a writable event on the main one.
         // We do this because a lost SYN takes a very long time
         // to repair at the TCP level.
         //
         // Failure to setup the timer is something we can live with,
         // so don't return an error in that case.
-        nsresult rv;
-        mSynTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-        if (NS_SUCCEEDED(rv)) {
-            mSynTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT);
-            LOG(("nsHalfOpenSocket::SetupBackupTimer() [this=%p]", this));
-        }
+        NS_NewTimerWithCallback(getter_AddRefs(mSynTimer),
+                                this, timeout, nsITimer::TYPE_ONE_SHOT);
+        LOG(("nsHalfOpenSocket::SetupBackupTimer() [this=%p]", this));
     } else if (timeout) {
         LOG(("nsHalfOpenSocket::SetupBackupTimer() [this=%p], did not arm\n", this));
     }
 }
 
 void
 nsHttpConnectionMgr::nsHalfOpenSocket::CancelBackupTimer()
 {
--- a/netwerk/protocol/websocket/WebSocketChannel.cpp
+++ b/netwerk/protocol/websocket/WebSocketChannel.cpp
@@ -260,28 +260,24 @@ public:
 
       if (fail) {
         TimeStamp rightNow = TimeStamp::Now();
 
         uint32_t remainingDelay = fail->RemainingDelay(rightNow);
         if (remainingDelay) {
           // reconnecting within delay interval: delay by remaining time
           nsresult rv;
-          ws->mReconnectDelayTimer =
-            do_CreateInstance("@mozilla.org/timer;1", &rv);
+          rv = NS_NewTimerWithCallback(getter_AddRefs(ws->mReconnectDelayTimer),
+                                       ws, remainingDelay, nsITimer::TYPE_ONE_SHOT);
           if (NS_SUCCEEDED(rv)) {
-            rv = ws->mReconnectDelayTimer->InitWithCallback(
-                          ws, remainingDelay, nsITimer::TYPE_ONE_SHOT);
-            if (NS_SUCCEEDED(rv)) {
-              LOG(("WebSocket: delaying websocket [this=%p] by %lu ms, changing"
-                   " state to CONNECTING_DELAYED", ws,
-                   (unsigned long)remainingDelay));
-              ws->mConnecting = CONNECTING_DELAYED;
-              return;
-            }
+            LOG(("WebSocket: delaying websocket [this=%p] by %lu ms, changing"
+                 " state to CONNECTING_DELAYED", ws,
+                 (unsigned long)remainingDelay));
+            ws->mConnecting = CONNECTING_DELAYED;
+            return;
           }
           // if timer fails (which is very unlikely), drop down to BeginOpen call
         } else if (fail->IsExpired(rightNow)) {
           mEntries.RemoveElementAt(failIndex);
           delete fail;
         }
       }
     }
@@ -1323,22 +1319,21 @@ WebSocketChannel::OnNetworkChanged()
     return NS_OK;
   }
 
   LOG(("nsWebSocketChannel:: Generating Ping as network changed\n"));
 
   if (!mPingTimer) {
     // The ping timer is only conditionally running already. If it wasn't
     // already created do it here.
-    nsresult rv;
-    mPingTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if (NS_FAILED(rv)) {
+    mPingTimer = NS_NewTimer();
+    if (!mPingTimer) {
       LOG(("WebSocket: unable to create ping timer!"));
       NS_WARNING("unable to create ping timer!");
-      return rv;
+      return NS_ERROR_OUT_OF_MEMORY;
     }
   }
   // Trigger the ping timeout asap to fire off a new ping. Wait just
   // a little bit to better avoid multi-triggers.
   mPingForced = 1;
   mPingTimer->InitWithCallback(this, 200, nsITimer::TYPE_ONE_SHOT);
 
   return NS_OK;
@@ -1423,25 +1418,19 @@ WebSocketChannel::BeginOpenInternal()
 
   if (NS_FAILED(rv)) {
     LOG(("WebSocketChannel::BeginOpenInternal: cannot async open\n"));
     AbortSession(NS_ERROR_CONNECTION_REFUSED);
     return;
   }
   mOpenedHttpChannel = 1;
 
-  mOpenTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  if (NS_FAILED(rv)) {
-    LOG(("WebSocketChannel::BeginOpenInternal: cannot create open timer\n"));
-    AbortSession(NS_ERROR_UNEXPECTED);
-    return;
-  }
-
-  rv = mOpenTimer->InitWithCallback(this, mOpenTimeout,
-                                    nsITimer::TYPE_ONE_SHOT);
+  rv = NS_NewTimerWithCallback(getter_AddRefs(mOpenTimer),
+                               this, mOpenTimeout,
+                               nsITimer::TYPE_ONE_SHOT);
   if (NS_FAILED(rv)) {
     LOG(("WebSocketChannel::BeginOpenInternal: cannot initialize open "
          "timer\n"));
     AbortSession(NS_ERROR_UNEXPECTED);
     return;
   }
 }
 
@@ -2130,21 +2119,20 @@ WebSocketChannel::PrimeNewOutgoingMessag
     if (mServerClosed) {
       /* bidi close complete */
       mReleaseOnTransmit = 1;
     } else if (NS_FAILED(mStopOnClose)) {
       /* result of abort session - give up */
       StopSession(mStopOnClose);
     } else {
       /* wait for reciprocal close from server */
-      mCloseTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-      if (NS_SUCCEEDED(rv)) {
-        mCloseTimer->InitWithCallback(this, mCloseTimeout,
-                                      nsITimer::TYPE_ONE_SHOT);
-      } else {
+      rv = NS_NewTimerWithCallback(getter_AddRefs(mCloseTimer),
+                                   this, mCloseTimeout,
+                                   nsITimer::TYPE_ONE_SHOT);
+      if (NS_FAILED(rv)) {
         StopSession(rv);
       }
     }
   } else {
     switch (msgType) {
     case kMsgTypePong:
       mOutHeader[0] = kFinalFragBit | nsIWebSocketFrame::OPCODE_PONG;
       break;
@@ -2445,21 +2433,20 @@ WebSocketChannel::StopSession(nsresult r
     //
     // Normally this will be taken care of in AbortSession() after mTCPClosed
     // is set when the server close arrives without waiting for the timeout to
     // expire.
 
     LOG(("WebSocketChannel::StopSession: Wait for Server TCP close"));
 
     nsresult rv;
-    mLingeringCloseTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if (NS_SUCCEEDED(rv))
-      mLingeringCloseTimer->InitWithCallback(this, kLingeringCloseTimeout,
-                                             nsITimer::TYPE_ONE_SHOT);
-    else
+    rv = NS_NewTimerWithCallback(getter_AddRefs(mLingeringCloseTimer),
+                                 this, kLingeringCloseTimeout,
+                                 nsITimer::TYPE_ONE_SHOT);
+    if (NS_FAILED(rv))
       CleanupConnection();
   } else {
     CleanupConnection();
   }
 
   if (mCancelable) {
     mCancelable->Cancel(NS_ERROR_UNEXPECTED);
     mCancelable = nullptr;
@@ -3012,23 +2999,24 @@ nsresult
 WebSocketChannel::StartPinging()
 {
   LOG(("WebSocketChannel::StartPinging() %p", this));
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mPingInterval);
   MOZ_ASSERT(!mPingTimer);
 
   nsresult rv;
-  mPingTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  if (NS_FAILED(rv)) {
-    NS_WARNING("unable to create ping timer. Carrying on.");
-  } else {
+  rv = NS_NewTimerWithCallback(getter_AddRefs(mPingTimer),
+                               this, mPingInterval,
+                               nsITimer::TYPE_ONE_SHOT);
+  if (NS_SUCCEEDED(rv)) {
     LOG(("WebSocketChannel will generate ping after %d ms of receive silence\n",
          mPingInterval));
-    mPingTimer->InitWithCallback(this, mPingInterval, nsITimer::TYPE_ONE_SHOT);
+  } else {
+    NS_WARNING("unable to create ping timer. Carrying on.");
   }
 
   return NS_OK;
 }
 
 
 void
 WebSocketChannel::ReportConnectionTelemetry()
--- a/netwerk/test/TestUDPSocket.cpp
+++ b/netwerk/test/TestUDPSocket.cpp
@@ -304,17 +304,17 @@ TEST(TestUDPSocket, TestUDPSocketMain)
   // Wait for server
   waiter->Wait(1);
   ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult));
 
   // Read response from server
   ASSERT_TRUE(NS_SUCCEEDED(clientListener->mResult));
 
   // Setup timer to detect multicast failure
-  nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1");
+  nsCOMPtr<nsITimer> timer = NS_NewTimer();
   ASSERT_TRUE(timer);
   RefPtr<MulticastTimerCallback> timerCb = new MulticastTimerCallback(waiter);
 
   // Join multicast group
   printf("Joining multicast group\n");
   phase = TEST_MULTICAST;
   mozilla::net::NetAddr multicastAddr;
   multicastAddr.inet.family = AF_INET;