54 lines
1.0 KiB
Dart
54 lines
1.0 KiB
Dart
import 'dart:async';
|
|
|
|
class SyncScheduler {
|
|
SyncScheduler({required Future<void> Function() onSync}) : _onSync = onSync;
|
|
|
|
final Future<void> Function() _onSync;
|
|
Timer? _timer;
|
|
bool _enabled = false;
|
|
Duration _interval = const Duration(minutes: 1);
|
|
bool _running = false;
|
|
|
|
void configure({required bool enabled, required Duration interval}) {
|
|
_enabled = enabled;
|
|
_interval = interval;
|
|
_restart();
|
|
}
|
|
|
|
void _restart() {
|
|
_timer?.cancel();
|
|
if (!_enabled) {
|
|
return;
|
|
}
|
|
_timer = Timer.periodic(_interval, (_) => triggerSync());
|
|
}
|
|
|
|
Future<void> triggerSync() async {
|
|
if (_running) {
|
|
return;
|
|
}
|
|
_running = true;
|
|
try {
|
|
await _onSync();
|
|
} finally {
|
|
_running = false;
|
|
}
|
|
}
|
|
|
|
Future<void> burstSync({
|
|
int count = 4,
|
|
Duration interval = const Duration(seconds: 2),
|
|
}) async {
|
|
for (var i = 0; i < count; i++) {
|
|
await triggerSync();
|
|
if (i + 1 < count) {
|
|
await Future.delayed(interval);
|
|
}
|
|
}
|
|
}
|
|
|
|
void dispose() {
|
|
_timer?.cancel();
|
|
}
|
|
}
|