Dart server check at intervals

Issue

I’m trying to run ‘checkServer’ at 5 second intervals. However ‘server is fine’ only runs once. What needs to be done to repeat the function?

import 'dart:io';
import 'dart:uri';
import 'dart:isolate';

checkServer() {
  HttpClient client = new HttpClient();
  HttpClientConnection connection = client.getUrl(...);

  connection.onResponse = (res) {
    ...
    print('server is fine');
    //client.shutdown();
  };

  connection.onError = ...;
}

main() {
  new Timer.repeating(5000, checkServer());
}

Solution

You have to give a void callback(Timer timer) as second parameter for Timer.repeating constructor.

With the following code, checkServer will be called every 5 seconds.

checkServer(Timer t) {
  // your code
}

main() {
  // schedule calls every 5 sec (first call in 5 sec)
  new Timer.repeating(5000, checkServer);

  // first call without waiting 5 sec
  checkServer(null);
}

Answered By – Alexandre Ardhuin

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.