JavaFX8 Timeline playing issue - javafx-8

I am using multiple Timelines in my application as
Timeline timeLine1 = new Timeline(new KeyFrame(Duration.seconds(1), actionEvent -> {
System.out.println("Enter in timer for check and playcontent");
MaintainPlaybackArray.checkAndPlayContent();
}));
timeLine1.setCycleCount(Timeline.INDEFINITE);
timeLine1.play();
Which will play each seconds
Timeline timeLine2 = new Timeline(new KeyFrame(Duration.seconds(5), actionEvent -> {
System.out.println("Enter in timer");
getSchedule();
checkSchedule();
}));
System.out.println("after timer");
timeLine2.setCycleCount(Timeline.INDEFINITE);
timeLine2.play();
Which Calls every 5 Seconds
Timeline timeLine3 = new Timeline(new KeyFrame(Duration.seconds(10), actionEvent -> {
System.out.println("in timer");
String currentChecksum = Util.md5(getScheduleJsonArray().toJSONString());
if (currentChecksum != null && !currentChecksum.equalsIgnoreCase(checksum)) {
System.out.println("Schedule changed");
isScheduleChanged = true;
checksum = currentChecksum;
}
}));
System.out.println("after timer");
timeLine3.setCycleCount(Timeline.INDEFINITE);
timeLine3.play();
which will executes after each 10 second.
Problem
When i execute the application after starting all the timelines it cannot play in synchronous manner.
i.e:
timLine1 will not executes for 8 seconds and then suddenly it executes 8 times at a time.
timeline2 will execute any time like after 8 seconds or twice after 12 seconds.
timeLine3 will executes after 12 seconds or 15 seconds.
So, Please help so that i can execute the code in synchronous manner.
is there anything i can use instead of Timeline?

Use ParallelTransition or SequentialTransition depending on your needs.

Related

Periodic background sync in PWA

I am new to periodic background sync, What I want to achieve is that my website should ping to the server at 5 hours of interval by doing so It will receive data from server which will then be processed. I wanted to know if it's possible to set minInterval in periodic background sync to 5 hours or we can't. If their is another method to achieve this can you please give me some source or even an code example might be good.
In this following example of MDN they have set it to one day. Can I reduce it to 5 hours.?
async function registerPeriodicNewsCheck() {
const registration = await navigator.serviceWorker.ready;
try {
await registration.periodicSync.register('get-latest-news', {
minInterval: 24 * 60 * 60 * 1000,
});
} catch {
console.log('Periodic Sync could not be registered!');
}
}
Thanks for your help.

How to set a time-specific event in Flutter?

I am trying to get a switch widget to turn off at a specific time of the day.
I have read a lot of the documentations like these
https://stackoverflow.com/questions/15848214/does-dart-have-a-scheduler
https://pub.dev/packages/cron
https://pub.dev/packages/scheduled_timer
All of these which can only allow me to set duration instead of a specific time.
Thus, my only approach right now is by setting up the timer when the switch is turned on.
e.g. 8hrs then it turns off.
Problem: If the user turned on the switch late, the time that it turns off will also be delayed.
So is there an actual way to set an event at a specific time + works even after we onstop/terminate the application?
You can try to do something like this:
I'll simplify the specific time into :
...
var setTime = DateTime.utc(2022, 7, 11, 8, 48, 0).toLocal();
StreamSubscription? subscription;
...
Then you can assign a periodic stream listener:
...
// periodic to run every second (you can change to minutes/hours/others too)
var stream = Stream.periodic(const Duration(seconds: 1), (count) {
//return true if the time now is after set time
return DateTime.now().isAfter(setTime);
});
//stream subscription
subscription = stream.listen((result) {
// if true, insert function and cancel listen subscription
if(result){
print('turn off');
subscription!.cancel();
}
// else if not yet, run this function
else {
print(result);
}
});
...
However, running a Dart code in a background process is more difficult, here are some references you can try:
https://medium.com/flutter/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124
https://pub.dev/packages/flutter_background_service
I hope it helps, feel free to comment if it doesn't work, I'll try my best to help.
After some time I figured it out.
Format
cron.schedule(Schedule.parse('00 00 * * *'), () async {
print("This code runs at 12am everyday")
});
More Examples
cron.schedule(Schedule.parse('15 * * * *'), () async {
print("This code runs every 15 minutes")
});
To customize a scheduler for your project, read this

Flutter stopwatchtimer doesn't respond to changing time

I use this package https://pub.dev/packages/stop_watch_timer in my app to keep track of the music that is playing. However if I want to change the song by changing the time on the stopwatch it says that I have to reset the timer first which I have already done. If I press the button for the second time it works. This is the code:
final StopWatchTimer _stopWatchTimer = StopWatchTimer(
mode: StopWatchMode.countUp,
onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
);
void change_timer_value(int song_index) {
int new_time = TimerState(
song_index: song_index,
record_side: current_side_list(
record_sides[selectedValue], widget.album_data))
.get_start_value();
print(new_time);
_stopWatchTimer.onExecute.add(StopWatchExecute.reset);
_stopWatchTimer.setPresetSecondTime(new_time); // this is where I set new time
}
I don't know how to get around this. I have already created an issue on the creators GitHub but no response. So there's somebody who can help me here
As you mentioned in the github issue, it looks like the root cause of your issue is that the reset action takes place asynchronously, and so hasn't gone through yet by the time you try to set the time.
One way to get around this is to define your own async function which resets the stopwatch, then waits for the action to complete before returning:
Future<void> _resetTimer() {
final completer = Completer<void>();
// Create a listener that will trigger the completer when
// it detects a reset event.
void listener(StopWatchExecute event) {
if (event == StopWatchExecute.reset) {
completer.complete();
}
}
// Add the listener to the timer's execution stream, saving
// the sub for cancellation
final sub = _stopWatchTimer.execute.listen(listener);
// Send the 'reset' action
_stopWatchTimer.onExecute.add(StopWatchExecute.reset);
// Cancel the sub after the future is fulfilled.
return completer.future.whenComplete(sub.cancel);
}
Usage:
void change_timer_value(int song_index) {
int new_time = TimerState(
song_index: song_index,
record_side: current_side_list(
record_sides[selectedValue], widget.album_data))
.get_start_value();
print(new_time);
_resetTimer().then(() {
_stopWatchTimer.setPresetSecondTime(new_time);
});
}
Or (with async/await):
void change_timer_value(int song_index) async {
int new_time = TimerState(
song_index: song_index,
record_side: current_side_list(
record_sides[selectedValue], widget.album_data))
.get_start_value();
print(new_time);
await _resetTimer();
_stopWatchTimer.setPresetSecondTime(new_time);
}

Ensure processing of a REST call in flutter app in background

I need to ensure that a certain HTTP request was send successfully. Therefore, I'm wondering if a simple way exists to move such a request into a background service task.
The background of my question is the following:
We're developing a survey application using flutter. Unfortunately, the app is intended to be used in an environment where no mobile internet connection can be guaranteed. Therefore, I’m not able to simply post the result of the survey one time but I have to retry it if it fails due to network problems. My current code looks like the following. The problem with my current solution is that it only works while the app is active all the time. If the user minimizes or closes the app, the data I want to upload is lost.
Therefore, I’m looking for a solution to wrap the upload process in a background service task so that it will be processed even when the user closes the app. I found several posts and plugins (namely https://medium.com/flutter-io/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124 and https://pub.dartlang.org/packages/background_fetch) but they don’t help in my particular use case. The first describes a way how the app could be notified when a certain event (namely the geofence occurred) and the second only works every 15 minutes and focuses a different scenario as well.
Does somebody knows a simple way how I can ensure that a request was processed even when there is a bad internet connection (or even none at the moment) while allowing the users to minimize or even close the app?
Future _processUploadQueue() async {
int retryCounter = 0;
Future.doWhile(() {
if(retryCounter == 10){
print('Abborted after 10 tries');
return false;
}
if (_request.uploaded) {
print('Upload ready');
return false;
}
if(! _request.uploaded) {
_networkService.sendRequest(request: _request.entry)
.then((id){
print(id);
setState(() {
_request.uploaded = true;
});
}).catchError((e) {
retryCounter++;
print(e);
});
}
// e ^ retryCounter, min 0 Sec, max 10 minutes
int waitTime = min(max(0, exp(retryCounter)).round(), 600);
print('Waiting $waitTime seconds till next try');
return new Future.delayed(new Duration(seconds: waitTime), () {
print('waited $waitTime seconds');
return true;
});
})
.then(print)
.catchError(print);
}
You can use the plugin shared_preferences to save each HTTP response to the device until the upload completes successfully. Like this:
requests: [
{
id: 8eh1gc,
request: "..."
},
...
],
Then whenever the app is launched, check if any requests are in the list, retry them, and delete them if they complete. You could also use the background_fetch to do this every 15 minutes.

GWT:can i put Delay for few seconds after showing a popup

I have small GWT application , in which i am showing a popup on success
if(success){
DescoratedPopupPanel popup = new DecoratedPopupPanel();
popup.show();
//Now here i want to wait for like 5 secs and then
popup.hide();
}
Any idea how can i put a dealay of 5 secs before hiding the popup
Thanks
Here is the code that uses Timer to produce 5 secs delay:
final DecoratedPopupPanel popup = new DecoratedPopupPanel();
popup.show();
// Now here i want to wait for like 5 secs and then
Timer timer = new Timer()
{
#Override
public void run()
{
popup.hide();
}
};
timer.schedule(5000);
You could use a com.google.gwt.user.client.Timer which lets you schedule a task in the future.
As Thomas Broyer mentioned in the comments, you could also use com.google.gwt.core.client.Scheduler#scheduleFixedDelay() with a RepeatingCommand that always returns false to indicate that it should only be executed once.