In this example, we are going to show how to schedule a background corn job in Flutter to execute some code or task repeatedly, or at some specific time. Corn job are important to schedule any task. See the example below:
First, add corn Flutter package to your project by adding the following lines on pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
cron: ^0.4.0
Import package to script:
import 'package:cron/cron.dart';
final cron = Cron();
cron.schedule(Schedule.parse('*/1 * * * *'), () async {
//your task code to execute
});
'*/1 * * * *'
is a corn job expression, some of the corn job expressions are:
Corn Job Expression Format:
* | * | * | * | * |
Minute | hour | day (month) | month | day (week) |
Some Corn Job Expressions:
Expression | Schedule |
*/1 * * * * | At every minute |
1 2 * * * | At 02:01. |
* */1 * * * | At every minute past every hour. |
1 * * */1 * | At minute 1 in every month. |
You can generate your own corn job expression at corntab.guru.
import 'package:cron/cron.dart';
import 'package:flutter/material.dart';
void main() {
runApp( MaterialApp(
home: Home()
));
}
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
int counter = 0;
final cron = Cron();
@override
void initState() {
scheduletask();
super.initState();
}
scheduletask(){
//schedule repeated corn job every 1 minute
cron.schedule(Schedule.parse('*/1 * * * *'), () async {
counter++;
setState(() {
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text("Schedule Corn Job"),
backgroundColor: Colors.deepPurpleAccent,
),
body: Container(
margin: EdgeInsets.only(top:30),
alignment: Alignment.center,
padding: EdgeInsets.all(20),
child: Column(
children: [
Text("Auto Counter: $counter", style:TextStyle(fontSize: 40)),
],
),
)
);
}
}
In this way, you can schedule a corn job in the Flutter app.
Please Wait...
No any Comments on this Article