profcollect: introduce a cool down window between trace events

This will be used to prevent traces from being taken too frequently and
negatively affects system performance.

Test: m services
Bug: 361001113
Change-Id: I14e0caf1bdc9432148ff318f5af054cc1ccc4ac1
diff --git a/services/profcollect/src/com/android/server/profcollect/Utils.java b/services/profcollect/src/com/android/server/profcollect/Utils.java
index b4e2544..a8016a0 100644
--- a/services/profcollect/src/com/android/server/profcollect/Utils.java
+++ b/services/profcollect/src/com/android/server/profcollect/Utils.java
@@ -25,10 +25,14 @@
 
 import com.android.internal.os.BackgroundThread;
 
+import java.time.Instant;
 import java.util.concurrent.ThreadLocalRandom;
 
 public final class Utils {
 
+    private static Instant lastTraceTime = Instant.EPOCH;
+    private static final int TRACE_COOLDOWN_SECONDS = 30;
+
     public static boolean withFrequency(String configName, int defaultFrequency) {
         int threshold = DeviceConfig.getInt(
                 DeviceConfig.NAMESPACE_PROFCOLLECT_NATIVE_BOOT, configName, defaultFrequency);
@@ -40,6 +44,9 @@
         if (mIProfcollect == null) {
             return false;
         }
+        if (isInCooldownOrReset()) {
+            return false;
+        }
         BackgroundThread.get().getThreadHandler().post(() -> {
             try {
                 mIProfcollect.trace_system(eventName);
@@ -54,6 +61,9 @@
         if (mIProfcollect == null) {
             return false;
         }
+        if (isInCooldownOrReset()) {
+            return false;
+        }
         BackgroundThread.get().getThreadHandler().postDelayed(() -> {
             try {
                 mIProfcollect.trace_system(eventName);
@@ -69,6 +79,9 @@
         if (mIProfcollect == null) {
             return false;
         }
+        if (isInCooldownOrReset()) {
+            return false;
+        }
         BackgroundThread.get().getThreadHandler().post(() -> {
             try {
                 mIProfcollect.trace_process(eventName,
@@ -80,4 +93,16 @@
         });
         return true;
     }
+
+    /**
+     * Returns true if the last trace is within the cooldown period. If the last trace is outside
+     * the cooldown period, the last trace time is reset to the current time.
+     */
+    private static boolean isInCooldownOrReset() {
+        if (!Instant.now().isBefore(lastTraceTime.plusSeconds(TRACE_COOLDOWN_SECONDS))) {
+            lastTraceTime = Instant.now();
+            return false;
+        }
+        return true;
+    }
 }