CodeBlanks Logo Icon CodeBlanks

OneOffTask

Schedule one-off tasks with OneOffTask.

What is OneOffTask?

OneOffTask represents a background task that runs once. It is registered with Workmanager().registerOneOffTask; the task runs once after a while. The first parameter is the task id and the second is the name passed to callbackDispatcher.

Workmanager().registerOneOffTask(
  'sync-task',
  'sync',
);

registerOneOffTask

The registerOneOffTask method schedules a one-time task. You tag the task with tag and provide a start delay with initialDelay. When the task runs, callbackDispatcher is called and the name in the second parameter arrives as task.

Workmanager().registerOneOffTask(
  'sync-task',
  'sync',
  initialDelay: Duration(seconds: 10),
);

Practice Register a one-off task

Register a task with Workmanager().registerOneOffTask using id 'sync-task' and callback name 'sync', and print 'ok'.

Starter code

main.dart
class Workmanager {
  void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
  void registerOneOffTask(String uniqueId, String taskName, {Duration? initialDelay}) {}
}

bool callbackDispatcher(String task) => true;

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

Sample solution

main.dart
class Workmanager {
  void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
  void registerOneOffTask(String uniqueId, String taskName, {Duration? initialDelay}) {}
}

bool callbackDispatcher(String task) => true;

void main() {
  Workmanager().registerOneOffTask('sync-task', 'sync');
  print('ok');
}

Expected output

ok

Questions and answers

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

1 How many times does OneOffTask run?

  • Continuously, at fixed intervals
  • Only once Correct answer
  • On every app launch
  • Never runs

Explanation: OneOffTask runs only once; for periodic execution you use PeriodicTask.

2 Register a one-off task

Question
Workmanager().____(
  'sync-task',
  'sync',
);
Answer
Workmanager().registerOneOffTask(
  'sync-task',
  'sync',
);

Explanation: To register a one-off task you call the registerOneOffTask method; the first parameter is the task id.

3 OneOffTask parts

Term Meaning
registerOneOffTask One-off registration
'sync-task' Task identifier
'sync' Callback name
initialDelay Initial delay

All lessons in Advanced