63 lines
1.6 KiB
Dart
63 lines
1.6 KiB
Dart
import 'dart:async';
|
|
import 'dart:io';
|
|
|
|
import '../pipeline/question_pipeline.dart';
|
|
import '../trading/trading_orchestrator.dart';
|
|
|
|
/// Runs [QuestionPipeline.runMaintenanceCycle] on a fixed interval, and
|
|
/// optionally [TradingOrchestrator.runMaintenanceCycle] right after when
|
|
/// trading is enabled.
|
|
class QuestionBackgroundWorker {
|
|
QuestionBackgroundWorker({
|
|
required QuestionPipeline pipeline,
|
|
required Duration interval,
|
|
TradingOrchestrator? tradingOrchestrator,
|
|
}) : _pipeline = pipeline,
|
|
_interval = interval,
|
|
_tradingOrchestrator = tradingOrchestrator;
|
|
|
|
final QuestionPipeline _pipeline;
|
|
final TradingOrchestrator? _tradingOrchestrator;
|
|
final Duration _interval;
|
|
Timer? _timer;
|
|
bool _running = false;
|
|
|
|
void start() {
|
|
if (_timer != null) {
|
|
return;
|
|
}
|
|
stdout.writeln(
|
|
'Question background worker started (interval ${_interval.inSeconds}s, '
|
|
'trading=${_tradingOrchestrator != null})',
|
|
);
|
|
_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');
|
|
}
|
|
if (_tradingOrchestrator != null) {
|
|
try {
|
|
await _tradingOrchestrator.runMaintenanceCycle();
|
|
} catch (e, st) {
|
|
stderr.writeln('Trading orchestrator tick failed: $e\n$st');
|
|
}
|
|
}
|
|
_running = false;
|
|
}
|
|
}
|