near final
This commit is contained in:
36
lib/backend/modules/synced_time.dart
Normal file
36
lib/backend/modules/synced_time.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import 'info_module.dart';
|
||||
|
||||
class SyncedTimeModule extends InfoModule {
|
||||
|
||||
int timeOffset = -1;
|
||||
DateTime lastUpdate = DateTime.now().add(const Duration(seconds: -15));
|
||||
|
||||
SyncedTimeModule() {
|
||||
refreshTimer();
|
||||
}
|
||||
|
||||
Timer refreshTimer() => Timer.periodic(const Duration(seconds: 10), (timer) async {
|
||||
var res = await http.get(Uri.parse('http://worldtimeapi.org/api/timezone/Europe/London'));
|
||||
if (res.statusCode == 200) {
|
||||
var json = jsonDecode(res.body);
|
||||
DateTime time = DateTime.parse(json['datetime']);
|
||||
timeOffset = time.millisecondsSinceEpoch - DateTime.now().millisecondsSinceEpoch;
|
||||
lastUpdate = DateTime.now();
|
||||
print("Time offset: $timeOffset");
|
||||
} else {
|
||||
print("Failed to get time from worldtimeapi.org");
|
||||
}
|
||||
});
|
||||
|
||||
DateTime Now() {
|
||||
if (timeOffset == -1) {
|
||||
return DateTime.now();
|
||||
}
|
||||
return DateTime.now().add(Duration(milliseconds: timeOffset));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user