Run time based job in flutter
Time based job are useful when you want to do job work in background upon on some time interval or even once without letting user know.
There is two easiest way to accomplish it.
- Timer
- Corn
Timer Class:
A count-down timer that can be configured to fire once or repeatedly.
Timer _timer;_callBack(Timer t) {{_doMyWork();print("timer called");t.cancel(); // canceled the time on 1st call only, execute only once}@overridevoid initState() {super.initState();_timer = Timer.periodic(Duration(minutes: 1), _callBack);}@overridevoid dispose() {if (_timer.isActive) _timer.cancel();super.dispose();}
Corn Lib:
Use Cron lib which will be run tasks periodically at fixed times or intervals. It's used for more complex time intervals, eg: if a task needs to be run on a specific time of an hour. let's see the diagram
The above diagram has an asterisk that represents a number that appears in a specific position.
import 'package:cron/cron.dart';
main() { var cron = new Cron(); cron.schedule(new Schedule.parse('*/1 * * * *'), () async { print('every minutes'); }); cron.schedule(new Schedule.parse('10-15 * * * *'), () async { print('between every 10 and 15 minutes'); });}
first '*' represents minutes, similar for the hour and so on as shown in the diagram.
Another example of the hour would be Schedule.parse(* 1,2,3,4 * * *)
, This schedule will run every minute every day during the hours of 1 AM, 2 AM, 3 AM, and 4 AM.
for more reference wiki/Cron
Bonus Point(Built-in Commands)
The build_runner package exposes a binary by the same name, which can be invoked using pub run build_runner <command>
--delete-conflicting-outputs: Assume conflicting outputs in the users package are from previous builds, and skip the user prompt that would usually be provided.
Example:
flutter packages pub run build_runner watch --delete-conflicting-outputs
Comments
Post a Comment