daily_limiter_util.dart 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'package:intl/intl.dart';
  2. import 'mmkv_util.dart';
  3. typedef LimitedAction = void Function();
  4. class DailyLimiterUtil {
  5. static Future<void> run({
  6. required String actionKey,
  7. required bool condition,
  8. required LimitedAction onExecute,
  9. int maxPerDay = 3,
  10. }) async {
  11. if (!condition) return;
  12. final today = DateFormat('yyyy-MM-dd').format(DateTime.now());
  13. final dateKey = '${actionKey}_date';
  14. final countKey = '${actionKey}_count';
  15. final savedDate = KVUtil.getString(dateKey, '');
  16. int execCount = KVUtil.getInt(countKey, 0);
  17. if (savedDate != today) {
  18. execCount = 0;
  19. KVUtil.putString(dateKey, today);
  20. KVUtil.putInt(countKey, execCount);
  21. }
  22. if (execCount < maxPerDay) {
  23. onExecute();
  24. KVUtil.putInt(countKey, execCount + 1);
  25. }
  26. }
  27. static void printSavedData(String actionKey) {
  28. final dateKey = '${actionKey}_date';
  29. final countKey = '${actionKey}_count';
  30. final savedDate = KVUtil.getString(dateKey, '');
  31. final execCount = KVUtil.getInt(countKey, 0);
  32. print("保存的日期: $savedDate");
  33. print("保存的执行次数: $execCount");
  34. }
  35. // 清除指定 actionKey 的日期和执行次数数据
  36. static void clearDailyLimitData(String actionKey) {
  37. final dateKey = '${actionKey}_date';
  38. final countKey = '${actionKey}_count';
  39. KVUtil.putString(dateKey, null);
  40. KVUtil.putInt(countKey, 0);
  41. print("已清除 $actionKey 的日期和执行次数数据");
  42. }
  43. }