Open nouveau-riche opened 2 years ago
This will work as like timer is working in flutter. the name cron
is populated from server stuff. but in here it has totally different scenario. It will work until the app is running.
does this package work on iOS?
import 'package:cron/cron.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class TokenSender {
static const _lastSentTokenKey = 'lastSentToken';
Future<void> sendToken() async {
final response = await http.post(Uri.parse('https://example.com/send-token'));
if (response.statusCode == 200) {
print('Токен отправлен успешно');
await _saveLastSentTokenTime(DateTime.now());
} else {
print('Ошибка при отправке токена: ${response.statusCode}');
}
}
Future<void> start() async {
final cron = Cron();
// Получаем время последней отправки токена из хранилища
final lastSentTokenTime = await _getLastSentTokenTime();
// Рассчитываем следующее время отправки токена
DateTime nextTokenTime = cron.next(Schedule.parse('0 10 * * 1'), from: lastSentTokenTime);
// Запускаем функцию sendToken() по расписанию
cron.schedule(Schedule.parse('0 10 * * 1'), () {
sendToken();
}, startsAt: nextTokenTime);
}
Future<DateTime> _getLastSentTokenTime() async {
final prefs = await SharedPreferences.getInstance();
final timestamp = prefs.getInt(_lastSentTokenKey);
return timestamp == null ? null : DateTime.fromMillisecondsSinceEpoch(timestamp);
}
Future<void> _saveLastSentTokenTime(DateTime time) async {
final prefs = await SharedPreferences.getInstance();
prefs.setInt(_lastSentTokenKey, time.millisecondsSinceEpoch);
}
}
Okay then here's the question Will the scheduled cron jobs persist between server restarts? Yes I am planning to use this in a server
Will the scheduled cron jobs persist between server restarts?
Cron has this intrinsic feature that the schedule is invariant of when you are setting it: if you are running something every two hours on the 25th minute of the hour (25 */2 * * *
), and you set this cron schedule at the start of your server application, then a server restart would also set it to happen on the next restart.
package:cron
is not designed for mobile app lifecycle, I have no idea how it works in that case. It was designed for long-lived server processes.