CodeBlanks Logo Icon CodeBlanks

PeriodicTask

Schedule periodic tasks with PeriodicTask.

What is PeriodicTask?

PeriodicTask represents a background task that repeats at fixed intervals. It is registered with Workmanager().registerPeriodicTask; the frequency parameter sets the repeat duration. The minimum interval varies by platform.

Workmanager().registerPeriodicTask(
  'sync-task',
  'sync',
  frequency: Duration(minutes: 15),
);

Constraints with constraints

You use Constraints to restrict when a PeriodicTask runs. For example, it can be set to run only when charging or when the network is connected. This saves battery and data.

Workmanager().registerPeriodicTask(
  'sync-task',
  'sync',
  frequency: Duration(minutes: 15),
  constraints: Constraints(
    networkType: NetworkType.connected,
  ),
);

Practice Register a periodic task

Register a task with Workmanager().registerPeriodicTask using id 'sync-task', callback name 'sync', and a 15 minute frequency, and print 'ok'.

Starter code

main.dart
class Workmanager {
  void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
  void registerPeriodicTask(String uniqueId, String taskName, {required Duration frequency}) {}
}

bool callbackDispatcher(String task) => true;

void main() {
  // periyodik görev kaydet
  // 'ok' yazdır
}

Sample solution

main.dart
class Workmanager {
  void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
  void registerPeriodicTask(String uniqueId, String taskName, {required Duration frequency}) {}
}

bool callbackDispatcher(String task) => true;

void main() {
  Workmanager().registerPeriodicTask(
    'sync-task',
    'sync',
    frequency: Duration(minutes: 15),
  );
  print('ok');
}

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which parameter specifies the repeat interval of PeriodicTask?

  • frequency Correct answer
  • tag
  • constraints
  • initialDelay

Explanation: The frequency parameter sets the repeat interval; initialDelay only sets the delay for the first run.

2 Register a periodic task

Question
Workmanager().____(
  'sync-task',
  'sync',
  frequency: Duration(minutes: 15),
);
Answer
Workmanager().registerPeriodicTask(
  'sync-task',
  'sync',
  frequency: Duration(minutes: 15),
);

Explanation: To register a periodic task you call the registerPeriodicTask method; the frequency parameter sets the repeat interval.

3 PeriodicTask parts

Term Meaning
registerPeriodicTask Periodic registration
frequency Repeat interval
Constraints Run constraints
NetworkType.connected When network is connected

All lessons in Advanced