1 | | | import 'dart:async'; |
2 | | |
|
3 | | | import 'cancellable_token.dart'; |
4 | | | import 'squadron_error.dart'; |
5 | | | import 'worker_exception.dart'; |
6 | | |
|
7 | | | /// Time-out cancellation tokens used by callers of worker services. The token is cancelled automatically after |
8 | | | /// a period of time indicated by [duration] with a countdown starting only when the task is assigned to a |
9 | | | /// platform worker. |
10 | | | class TimeOutToken extends CancellableToken { |
11 | | 2 | TimeOutToken(this.duration, [String? message]) : super(message); |
12 | | |
|
13 | | | /// Throws an exception, time-out tokens may not be cancelled programmatically. |
14 | | 1 | @override |
15 | | 2 | void cancel() => throw newSquadronError( |
16 | | 1 | 'TimeOutToken cannot be cancelled programmatically'); |
17 | | |
|
18 | | | /// Duration of the timeout. The timer is not started before task is scheduled on a platform worker. |
19 | | | final Duration duration; |
20 | | |
|
21 | | | Timer? _timer; |
22 | | |
|
23 | | | /// Called just before processing a [WorkerRequest]. The [onTimeout] callback may not be null, and a timer will be |
24 | | | /// started that will automatically cancel this token if processing takes longer than [duration]. |
25 | | 1 | @override |
26 | | 3 | void start() => _timer ??= Timer( |
27 | | 2 | duration, |
28 | | 3 | () => super.setException( |
29 | | 4 | TaskTimeoutException(message: message, duration: duration))); |
30 | | |
|
31 | | | /// Returns `true` if the timeout has started, `false` otherwise. |
32 | | 2 | bool get started => _timer != null; |
33 | | | } |