How to run on a schedule by flutter - flutter

I want to create timer app on flutter, I can't know how to schedul of run.
If you know how to do that,Would like to tell me.
This sentence was transrated,so I'm sorry if mistaken.

You can try this:
void main() {
scheduleTimeout(5 * 1000); // 5 seconds.
}
Timer scheduleTimeout([int milliseconds = 10000]) =>
Timer(Duration(milliseconds: milliseconds), handleTimeout);
void handleTimeout() { // callback function
// Do some work.
}
This function waits 5 seconds before it calls the callback handleTimeout.
Refer to this: https://api.flutter.dev/flutter/dart-async/Timer-class.html

You might try to use the work manager plugin.
workmanager. Even when the app is closed, it will execute task even when app is closed.
For ex:
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) {
print("Native called background task: $backgroundTask"); //simpleTask will be emitted here.
return Future.value(true);
});
}
void main() {
Workmanager().initialize(
callbackDispatcher, // The top level function, aka callbackDispatcher
isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
);
Workmanager().registerOneOffTask("task-identifier", "simpleTask");
runApp(MyApp());
}

You can use Timer function to achieve schedule

Related

Is it good approach to cancel WorkManger task in executeTask() function in flutter

I have to cancel/dispose workmanager task as soon as it gets completed, but most of the times app is not in running state. So is it good or bad to cancel that task in executeTask() function.
Here is code example:
Register task first
Workmanager().registerOneOffTask('taskABC','taskABC',
inputData: {'data':'some data here'},);
And here is an code inside callbackDispathcer()
Workmanager().executeTask((taskName, inputData) async {
try {
switch(taskName) {
case 'taskABC':
//do something here
Workmanager().cancelByUniqueName('taskABC');
break;
}
return true;
} catch(e) {
debugPrint('---> Error in work manager execution taskName[$taskName] with inputData[$inputData] | Exception: $e');
return false;
}});
I just need to know what could be the best way to cancel/dispose a task, when the app is not in running state.

Cancel execution of method after it starts in Flutter

Consider this method:
Future<void> methodWithAlotOfSteps()async{
callMethodA();
await callMethodB();
...
return ...;
}
which makes some computation. Suppose I want the user to be able to stop this process at any point in time (when he taps cancel button for example).
How can I stop the execution of the above method no matter what line in the method the "program counter" has reached when the user presses cancel.
I am looking for something like methodWithAlotOfSteps.cancel();.
I tried using CancelableCompleter, but even though the Future is cancelled and onCancel method of the completer is called, but the function continues execution.
I know I can set a boolean flag and check it after each "step" ("line", "call to a method"),such as :
Future<void> methodWithAlotOfSteps()async{
if(!completer.isCancelled)
callMethodA();
if(!completer.isCancelled)
await callMethodB();
...
return ...;
}
but is there a better way of doing this?
As #Jamesdlin suggested, the apparent way is to check the cancelable completer's state after each async gap:
class MyService{
CancelableCompleter completer = CancelableCompleter();
Future<void> doSomething() async {
doSomeSyncWork(); // Sync work
doAnotherSyncWork(); // Sync work
await doSomeAsyncWork(); // Async work, this will return control to event loop and make it possible to, for example, press a button to cancel the future.
// here we know we have lost control for a while, so we must check if we have been cancelled
if (completer.isCompleted) {
return;
}
doSomeMoreSyncWork();
await doSomeMoreAsyncWork();
// here we know we have lost control for a while, so we must check if we have been cancelled
if (completer.isCompleted) {
return;
}
...
completer.complete();
}
}

How do I get a dart Stream with uneven intervals?

I'm new to dart and Flutter and would love to get some advice on an algorithmic problem I'm facing.
I want to connect my Flutter app to a bluetooth device (that part is done, I am connected already) and send messages on uneven intervals. I have the messages in a list and for each of them I know at what time (milliseconds) I want to send the message.
So suppose the following messages are lined up:
start at 0ms
init_app at 100ms
user_pick_x at 500ms
user_start_x at 500ms (will be sent after user_pick_x, order should be guaranteed)
interrupt at 3500ms
I have found the documentation to create streams, but it always talks about a single interval value. https://dart.dev/articles/libraries/creating-streams.
Ideas:
Technically I can pass in a list of Duration objects and work with a custom generator async*, along with the message string.
Alternatively I can set the interval to the lowest time delta and check on each one whether a message / messages should be sent. In the case of the example that would be every 100ms.
It would be nice to be able to pause / cancel the stream as well. Which is something that streams can do natively.
I think the easiest is to just emit those messages at the specified intervals. Something like:
Future<void> _wait(int milliseconds) async =>
await Future<void>.delayed(Duration(milliseconds: milliseconds));
Stream<String> generateMessages() async* {
yield 'start';
await _wait(100);
yield 'init_all';
await _wait(400);
yield 'user_pick_x';
yield 'user_start_x';
await _wait(3000);
yield 'interrupt';
}
void main() {
generateMessages().listen((msg) {
print('${DateTime.now()}: $msg');
});
}
which will print:
2021-07-25 10:21:21.429: start
2021-07-25 10:21:21.531: init_all
2021-07-25 10:21:21.934: user_pick_x
2021-07-25 10:21:21.934: user_start_x
2021-07-25 10:21:24.938: interrupt
If you want to make sure that the listener of the stream receives events asynchronously - hence not interfering with the wait milliseconds, you can explicitly use the StreamController which by default calls the listeners asynchronously (make sure to import dart:async --- dart:io is only used in the example for the sleep to show that even on a blocking action it will run in parallel with the waiting):
import 'dart:async';
import 'dart:io';
Future<void> _wait(int milliseconds) async {
print('WAIT $milliseconds ms');
await Future<void>.delayed(Duration(milliseconds: milliseconds));
}
Stream<String> generateMessages() {
final controller = StreamController<String>(sync: false);
controller.onListen = () async {
controller.add('start');
await _wait(100);
controller.add('init_all');
await _wait(400);
controller.add('user_pick_x');
controller.add('user_start_x');
await _wait(3000);
controller.add('interrupt');
};
return controller.stream;
}
void main() {
generateMessages().listen((msg) {
sleep(const Duration(milliseconds: 120));
print('${DateTime.now()}: $msg');
});
}

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);
}

How to perform Async await in the below code

I need clarifications about how to solve the below code using async and await and future API in dart.
void main()
{
print("Program starts");
printdart(1);
print("Program finishes");
}
printdart(int temp)
{
int i;
for(i=temp;i<=1000;i++)
{
print("dart");
if(i%10==0)
{
printangular(i+1);
break;
}
}
}
printangular(int temp)
{
int i;
for(i=temp;i<=1000;i++)
{
print("angular");
if(i%10==0)
{
printdart(i+1);
break;
}
}
}
How to implement async and await in dart
I think you need to study more how Dart deals with Threads. I can't explain everything here, but basically Dart runs only one Thread, so all your code will just block that Thread, async awit won't help you.
Dart also have Isolates, that can run in multiple threads, but since they are very isolated, it's not easy to pass and get data from them.
Async/await works best with network requests and file access, because they block once activated, so the Thread can just ignore them for now and go back there when there's a new value. Your code in the other hand doesn't block, so you can't await for it.
There's one way though, you need to refractor your code so it will yield values, and you can async await them. In this case you need to read about Async Generators and see how they work so you can reformat your code accordingly.
In the code you provided, there is no waiting for the code to do some heavy process.
Below is a modified version of your code. Here, the code will wait for some time before it is called again. In the meantime rest of the code is executed.
import 'dart:async';
void main() {
print("Program starts");
printdart();
printangular();
print("Program finishes");
}
printdart() async {
int i;
for (i = 1; i <= 4; i++) {
print("dart");
await Future.delayed(const Duration(seconds: 2));
}
}
printangular() async {
int i;
for (i = 1; i <= 4; i++) {
print("angular");
await Future.delayed(const Duration(seconds: 1));
}
}
To answer your question:
async: a keyword to tell the compiler that the function will take some time to complete but in the meantime, go back and run the next part of the program and come back when this function is done.
await: this allows waiting for the process to complete before jumping to immediate next line.