How to Execute Code on Loop With Time Interval (Timer)

In this example, we are going to show you the way to execute or call code, functions on loop with time interval. For example, you want to call some function every 5 seconds, then see the example below to learn how to set Time Interval in Flutter App.

To Use Timer, import the following dart library:

import 'dart:async';

Timer mytimer = Timer.periodic(Duration(seconds: 5), (timer) {
  //code to run on every 5 seconds
});

Timer mytimer = Timer.periodic(Duration(minutes:2, seconds: 5), (timer) {
  //code to run on every 2 minutes 5 seconds
});

Timer mytimer = Timer.periodic(Duration(hours:2, minutes: 30), (timer) {
  //cde to run on every 2 hours and 30 minutes
});

Timer mytimer = Timer.periodic(Duration(seconds: 5), (timer) {
  //code to run on every 5 seconds
});

mytimer.cancel(); //to end timer

You can add more attributes to Duration() widget such as day, hours, minutes, seconds, microseconds, milliseconds. 

import 'dart:async';
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget{
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String time = "";

   @override
  void initState() {
     Timer mytimer = Timer.periodic(Duration(seconds: 1), (timer) {
        DateTime timenow = DateTime.now();  //get current date and time
        time = timenow.hour.toString() + ":" + timenow.minute.toString() + ":" + timenow.second.toString(); 
        setState(() {
          
        });
        //mytimer.cancel() //to terminate this timer
     });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold(
        appBar: AppBar(
            title:Text("Execute Code With Timer"),
            backgroundColor: Colors.redAccent,
        ),
        body: Container(
          height: 260,
          color: Colors.red.shade50,
          child: Center(
            child: Text(time, style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),
            //show time on UI
          )
        )
      )
    );
  }
}

In this way, you can set time intervals using Timer in Flutter to execute code on loop.

1 Commet on this Article

Ashok Chandra

Hello Sir/Ma’am,

I am used this code this is very useful thanks for sharing it. But when I am putting a function there so code is showing error. 

Please do the nedfuly.

Thanks & Regards,

ASHOK CHANDRA

1 year ago


Please Wait...