50 lines
1.1 KiB
Dart
50 lines
1.1 KiB
Dart
import 'dart:async';
|
|
import 'dart:io';
|
|
|
|
import '../pipeline/question_pipeline.dart';
|
|
|
|
/// Runs [QuestionPipeline.runMaintenanceCycle] on a fixed interval.
|
|
class QuestionBackgroundWorker {
|
|
QuestionBackgroundWorker({
|
|
required QuestionPipeline pipeline,
|
|
required Duration interval,
|
|
}) : _pipeline = pipeline,
|
|
_interval = interval;
|
|
|
|
final QuestionPipeline _pipeline;
|
|
final Duration _interval;
|
|
Timer? _timer;
|
|
bool _running = false;
|
|
|
|
void start() {
|
|
if (_timer != null) {
|
|
return;
|
|
}
|
|
stdout.writeln(
|
|
'Question background worker started (interval ${_interval.inSeconds}s)',
|
|
);
|
|
_timer = Timer.periodic(_interval, (_) => _tick());
|
|
unawaited(_tick());
|
|
}
|
|
|
|
void stop() {
|
|
_timer?.cancel();
|
|
_timer = null;
|
|
_pipeline.close();
|
|
}
|
|
|
|
Future<void> _tick() async {
|
|
if (_running) {
|
|
return;
|
|
}
|
|
_running = true;
|
|
try {
|
|
await _pipeline.runMaintenanceCycle();
|
|
} catch (e, st) {
|
|
stderr.writeln('Question background worker tick failed: $e\n$st');
|
|
} finally {
|
|
_running = false;
|
|
}
|
|
}
|
|
}
|