Rework Timer interface.

Review URL: https://codereview.chromium.org//12213092

git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart@18326 260f80e4-7a28-3924-810f-c04153c831b5
This commit is contained in:
floitsch@google.com 2013-02-11 19:22:16 +00:00
parent 0ea0b1ef63
commit 3f7146707d
53 changed files with 276 additions and 189 deletions

View file

@ -90,19 +90,19 @@
* test('callback is executed once', () {
* // wrap the callback of an asynchronous call with [expectAsync0] if
* // the callback takes 0 arguments...
* var timer = new Timer(0, (_) => expectAsync0(() {
* var timer = Timer.run(expectAsync0(() {
* int x = 2 + 3;
* expect(x, equals(5));
* }));
* });
*
* test('callback is executed twice', () {
* var callback = (_) => expectAsync0(() {
* var callback = expectAsync0(() {
* int x = 2 + 3;
* expect(x, equals(5));
* }, count: 2); // <-- we can indicate multiplicity to [expectAsync0]
* new Timer(0, callback);
* new Timer(0, callback);
* Timer.run(callback);
* Timer.run(callback);
* });
* }
*
@ -131,7 +131,7 @@
* test('callback is executed', () {
* // indicate ahead of time that an async callback is expected.
* var async = startAsync();
* new Timer(0, (_) {
* Timer.run(() {
* // Guard the body of the callback, so errors are propagated
* // correctly.
* guardAsync(() {

View file

@ -26,7 +26,7 @@ void shouldFail(value, Matcher matcher, expected, {bool isAsync: false}) {
errorCount = 0;
errorString = '';
expect(value, matcher);
afterTest(_) {
afterTest() {
configureExpectFailureHandler(null);
expect(errorCount, equals(1));
if (expected is String) {
@ -37,9 +37,9 @@ void shouldFail(value, Matcher matcher, expected, {bool isAsync: false}) {
}
if (isAsync) {
new Timer(0, expectAsync1(afterTest));
Timer.run(expectAsync0(afterTest));
} else {
afterTest(null);
afterTest();
}
}
@ -48,13 +48,13 @@ void shouldPass(value, Matcher matcher, {bool isAsync: false}) {
errorCount = 0;
errorString = '';
expect(value, matcher);
afterTest(_) {
afterTest() {
configureExpectFailureHandler(null);
expect(errorCount, equals(0));
}
if (isAsync) {
new Timer(0, expectAsync1(afterTest));
Timer.run(expectAsync0(afterTest));
} else {
afterTest(null);
afterTest();
}
}

View file

@ -2,23 +2,40 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
typedef void _TimerCallback0();
typedef void _TimerCallback1(Timer timer);
patch class Timer {
/* patch */ factory Timer(int milliseconds, void callback(Timer timer)) {
/* patch */ factory Timer(var duration, Function callback) {
// TODO(floitsch): remove these checks when we remove the deprecated
// millisecond argument and the 1-argument callback. Also remove
// the int-test below.
if (callback is! _TimerCallback0 && callback is! _TimerCallback1) {
throw new ArgumentError(callback);
}
int milliseconds = duration is int ? duration : duration.inMilliseconds;
if (milliseconds < 0) milliseconds = 0;
_TimerCallback1 oneArgumentCallback =
callback is _TimerCallback1 ? callback : (_) { callback(); };
if (_TimerFactory._factory == null) {
throw new UnsupportedError("Timer interface not supported.");
}
return _TimerFactory._factory(milliseconds, callback, false);
return _TimerFactory._factory(milliseconds, oneArgumentCallback, false);
}
/**
* Creates a new repeating timer. The [callback] is invoked every
* [milliseconds] millisecond until cancelled.
*/
/* patch */ factory Timer.repeating(int milliseconds,
/* patch */ factory Timer.repeating(var duration,
void callback(Timer timer)) {
if (_TimerFactory._factory == null) {
throw new UnsupportedError("Timer interface not supported.");
}
// TODO(floitsch): remove this check when we remove the deprecated
// millisecond argument.
int milliseconds = duration is int ? duration : duration.inMilliseconds;
if (milliseconds < 0) milliseconds = 0;
return _TimerFactory._factory(milliseconds, callback, true);
}
}

View file

@ -6,16 +6,35 @@
import 'dart:_isolate_helper' show TimerImpl;
typedef void _TimerCallback0();
typedef void _TimerCallback1(Timer timer);
patch class Timer {
patch factory Timer(int milliseconds, void callback(Timer timer)) {
return new TimerImpl(milliseconds, callback);
patch factory Timer(var duration, var callback) {
// TODO(floitsch): remove these checks when we remove the deprecated
// millisecond argument and the 1-argument callback. Also remove the
// int-test below.
if (callback is! _TimerCallback0 && callback is! _TimerCallback1) {
throw new ArgumentError(callback);
}
int milliseconds = duration is int ? duration : duration.inMilliseconds;
if (milliseconds < 0) milliseconds = 0;
Timer timer;
_TimerCallback0 zeroArgumentCallback =
callback is _TimerCallback0 ? callback : () => callback(timer);
timer = new TimerImpl(milliseconds, zeroArgumentCallback);
return timer;
}
/**
* Creates a new repeating timer. The [callback] is invoked every
* [milliseconds] millisecond until cancelled.
*/
patch factory Timer.repeating(int milliseconds, void callback(Timer timer)) {
patch factory Timer.repeating(var duration, void callback(Timer timer)) {
// TODO(floitsch): remove this check when we remove the deprecated
// millisecond argument.
int milliseconds = duration is int ? duration : duration.inMilliseconds;
if (milliseconds < 0) milliseconds = 0;
return new TimerImpl.repeating(milliseconds, callback);
}
}

View file

@ -313,7 +313,7 @@ class _EventLoop {
// Run each iteration from the browser's top event loop.
void next() {
if (!runIteration()) return;
new Timer(0, (_) => next());
Timer.run(next);
}
next();
} else {
@ -1264,7 +1264,7 @@ class TimerImpl implements Timer {
bool _inEventLoop = false;
int _handle;
TimerImpl(int milliseconds, void callback(Timer timer))
TimerImpl(int milliseconds, void callback())
: _once = true {
if (milliseconds == 0 && (!hasTimer() || _globalState.isWorker)) {
// This makes a dependency between the async library and the
@ -1273,14 +1273,13 @@ class TimerImpl implements Timer {
// TODO(7907): In case of web workers, we need to use the event
// loop instead of setTimeout, to make sure the futures get executed in
// order.
_globalState.topEventLoop.enqueue(_globalState.currentContext, () {
callback(this);
}, 'timer');
_globalState.topEventLoop.enqueue(
_globalState.currentContext, callback, 'timer');
_inEventLoop = true;
} else if (hasTimer()) {
_globalState.topEventLoop.activeTimerCount++;
void internalCallback() {
callback(this);
callback();
_handle = null;
_globalState.topEventLoop.activeTimerCount--;
}

View file

@ -82,7 +82,7 @@ class _InstanceMirror extends InstanceMirror {
var completer = new Completer<InstanceMirror>();
// TODO(ahe): [Completer] or [Future] should have API to create a
// delayed action. Simulating with a [Timer].
new Timer(0, (timer) {
Timer.run(() {
if (JS('String', 'typeof #', method) == 'function') {
var result =
JS('var', '#.apply(#, #)', method, reflectee, jsList);

View file

@ -59,7 +59,7 @@ class AsyncError {
}
try {
new Timer(0, (_) {
Timer.run(() {
reportError();
// TODO(floitsch): we potentially want to call the global error handler
// directly so that we can pass the stack trace.

View file

@ -42,7 +42,7 @@ part of dart.async;
* this potential bug:
*
* var future = getFuture();
* new Timer(5, (_) {
* new Timer(new Duration(milliseconds: 5), () {
* // The error-handler is only attached 5ms after the future has been
* // received. If the future fails in the mean-time it will forward the
* // error to the global error-handler, even though there is code (just

View file

@ -179,14 +179,14 @@ class _FutureImpl<T> implements Future<T> {
_addListener(whenFuture);
} else if (_hasValue) {
T value = _resultOrListeners;
new Timer(0, (_) {
Timer.run(() {
whenFuture._sendValue(value);
});
} else {
assert(_hasError);
_clearUnhandledError();
AsyncError error = _resultOrListeners;
new Timer(0, (_) {
Timer.run(() {
whenFuture._sendError(error);
});
}
@ -198,7 +198,7 @@ class _FutureImpl<T> implements Future<T> {
assert(_hasValue);
_ThenFuture thenFuture = new _ThenFuture(onValue);
T value = _resultOrListeners;
new Timer(0, (_) { thenFuture._sendValue(value); });
Timer.run(() { thenFuture._sendValue(value); });
return thenFuture;
}
@ -208,7 +208,7 @@ class _FutureImpl<T> implements Future<T> {
_clearUnhandledError();
AsyncError error = _resultOrListeners;
_CatchErrorFuture errorFuture = new _CatchErrorFuture(onError, test);
new Timer(0, (_) { errorFuture._sendError(error); });
Timer.run(() { errorFuture._sendError(error); });
return errorFuture;
}
@ -248,7 +248,7 @@ class _FutureImpl<T> implements Future<T> {
_state |= _UNHANDLED_ERROR;
// Wait for the rest of the current event's duration to see
// if a subscriber is added to handle the error.
new Timer(0, (_) {
Timer.run(() {
if (_hasUnhandledError) {
// No error handler has been added since the error was set.
_clearUnhandledError();

View file

@ -1026,7 +1026,7 @@ abstract class _PendingEvents {
void schedule(_StreamImpl stream) {
if (isScheduled) return;
scheduleTimer = new Timer(0, (_) {
scheduleTimer = Timer.run(() {
scheduleTimer = null;
stream._handlePendingEvents();
});
@ -1084,7 +1084,7 @@ class _DoneSubscription<T> implements StreamSubscription<T> {
void _delayDone() {
assert(_timer == null && _pauseCount == 0);
_timer = new Timer(0, (_) {
_timer = Timer.run(() {
if (_handler != null) _handler();
});
}

View file

@ -6,18 +6,55 @@ part of dart.async;
abstract class Timer {
/**
* Creates a new timer. The [callback] callback is invoked after
* [milliseconds] milliseconds.
* Creates a new timer.
*
* The [callback] callback is invoked after the given [duration]
* (a [Duration]) has passed. A negative duration is treated similar to
* a duration of 0.
*
* If the [duration] is statically known to be 0, consider using [run].
*
* Frequently the [duration] is either a constant or computed as in the
* following example (taking advantage of the multiplication operator of
* the Duration class):
*
* const TIMEOUT = const Duration(seconds: 3);
* const ms = const Duration(milliseconds: 1);
*
* startTimeout([int milliseconds]) {
* var duration = milliseconds == null ? TIMEOUT : ms * milliseconds;
* return new Timer(duration, handleTimeout);
* }
*
* *Deprecation warning*: this constructor used to take an [int] (the time
* in milliseconds) and a callback with one argument (the timer). This has
* changed to a [Duration] and a callback without arguments.
*/
external factory Timer(int milliseconds, void callback(Timer timer));
// TODO(floitsch): add types.
external factory Timer(var duration, Function callback);
/**
* Creates a new repeating timer. The [callback] is invoked every
* [milliseconds] millisecond until cancelled.
* Creates a new repeating timer.
*
* The [callback] is invoked repeatedly with [duration] intervals until
* canceled. A negative duration is treated similar to a duration of 0.
*
* *Deprecation warning*: this constructor used to take an [int] (the time
* in milliseconds). This has changed to a [Duration].
*/
external factory Timer.repeating(int milliseconds,
external factory Timer.repeating(var duration,
void callback(Timer timer));
/**
* Runs the given [callback] asynchronously as soon as possible.
*
* Returns a [Timer] that can be cancelled if the callback is not necessary
* anymore.
*/
static Timer run(void callback()) {
return new Timer(const Duration(), callback);
}
/**
* Cancels the timer.
*/

View file

@ -92,7 +92,7 @@ class _ChunkedInputStream implements ChunkedInputStream {
void _checkScheduleCallback() {
// TODO(sgjesse): Find a better way of scheduling callbacks from
// the event loop.
void issueDataCallback(Timer timer) {
void issueDataCallback() {
_scheduledDataCallback = null;
if (_clientDataHandler != null) {
_clientDataHandler();
@ -100,7 +100,7 @@ class _ChunkedInputStream implements ChunkedInputStream {
}
}
void issueCloseCallback(Timer timer) {
void issueCloseCallback() {
_scheduledCloseCallback = null;
if (!_closed) {
if (_clientCloseHandler != null) _clientCloseHandler();
@ -113,7 +113,7 @@ class _ChunkedInputStream implements ChunkedInputStream {
(_bufferList.length > 0 && _inputClosed)) &&
_clientDataHandler != null &&
_scheduledDataCallback == null) {
_scheduledDataCallback = new Timer(0, issueDataCallback);
_scheduledDataCallback = Timer.run(issueDataCallback);
}
// Schedule close callback if no more data and input is closed.
@ -124,7 +124,7 @@ class _ChunkedInputStream implements ChunkedInputStream {
if (_scheduledDataCallback != null) {
_scheduledDataCallback.cancel();
}
_scheduledCloseCallback = new Timer(0, issueCloseCallback);
_scheduledCloseCallback = Timer.run(issueCloseCallback);
}
}

View file

@ -224,7 +224,7 @@ class _FileOutputStream extends _BaseOutputStream implements OutputStream {
outstandingWrites == 0 &&
!_streamMarkedClosed &&
_onNoPendingWrites != null) {
new Timer(0, (t) {
Timer.run(() {
if (_onNoPendingWrites != null) {
_onNoPendingWrites();
}
@ -444,7 +444,7 @@ class _File extends _FileBase implements File {
if (mode != FileMode.READ &&
mode != FileMode.WRITE &&
mode != FileMode.APPEND) {
new Timer(0, (t) {
Timer.run(() {
completer.completeError(new ArgumentError());
});
return completer.future;
@ -665,7 +665,7 @@ class _File extends _FileBase implements File {
completer.completeError(e);
};
} catch (e) {
new Timer(0, (t) => completer.completeError(e));
Timer.run(() => completer.completeError(e));
return completer.future;
}
return completer.future;
@ -685,7 +685,7 @@ class _File extends _FileBase implements File {
return writeAsBytes(data, mode);
} catch (e) {
var completer = new Completer();
new Timer(0, (t) => completer.completeError(e));
Timer.run(() => completer.completeError(e));
return completer.future;
}
}
@ -787,7 +787,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
// Complete asynchronously so the user has a chance to setup
// handlers without getting exceptions when registering the
// then handler.
new Timer(0, (t) {
Timer.run(() {
completer.completeError(new FileIOException(
"Invalid arguments to read for file '$_name'"));
});
@ -824,7 +824,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
// Complete asynchronously so the user has a chance to setup
// handlers without getting exceptions when registering the
// then handler.
new Timer(0, (t) {
Timer.run(() {
completer.completeError(new FileIOException(
"Invalid arguments to readList for file '$_name'"));
});
@ -880,7 +880,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
// Complete asynchronously so the user has a chance to setup
// handlers without getting exceptions when registering the
// then handler.
new Timer(0, (t) {
Timer.run(() {
completer.completeError(new FileIOException(
"Invalid argument to writeByte for file '$_name'"));
});
@ -923,7 +923,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
// Complete asynchronously so the user has a chance to setup
// handlers without getting exceptions when registering the
// then handler.
new Timer(0, (t) {
Timer.run(() {
completer.completeError(new FileIOException(
"Invalid arguments to writeList for file '$_name'"));
});
@ -938,7 +938,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
// Complete asynchronously so the user has a chance to setup
// handlers without getting exceptions when registering the
// then handler.
new Timer(0, (t) => completer.completeError(e));
Timer.run(() => completer.completeError(e));
return completer.future;
}
@ -981,7 +981,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
[Encoding encoding = Encoding.UTF_8]) {
if (encoding is! Encoding) {
var completer = new Completer();
new Timer(0, (t) {
Timer.run(() {
completer.completeError(new FileIOException(
"Invalid encoding in writeString: $encoding"));
});
@ -1151,7 +1151,7 @@ class _RandomAccessFile extends _FileBase implements RandomAccessFile {
}
Future _completeWithClosedException(Completer completer) {
new Timer(0, (t) {
Timer.run(() {
completer.completeError(
new FileIOException("File closed '$_name'"));
});

View file

@ -502,7 +502,7 @@ class _HttpResponse extends _HttpRequestResponseBase implements HttpResponse {
// Indicate to the connection that the response handling is done.
_httpConnection._responseClosed();
if (_streamClosedHandler != null) {
new Timer(0, (_) => _streamClosedHandler());
Timer.run(_streamClosedHandler);
}
}
@ -1213,7 +1213,7 @@ class _HttpClientRequest
_writeDone();
_connection._requestClosed();
if (_streamClosedHandler != null) {
new Timer(0, (_) => _streamClosedHandler());
Timer.run(_streamClosedHandler);
}
}
@ -2056,7 +2056,7 @@ class _HttpClient implements HttpClient {
_SocketConnection socketConn = socketConnections.removeFirst();
socketConn._markRetrieved();
_activeSockets.add(socketConn);
new Timer(0, (ignored) =>
Timer.run(() =>
_connectionOpened(socketConn, connection, !proxy.isDirect));
// Get rid of eviction timer if there are no more active connections.
@ -2151,7 +2151,8 @@ class _HttpClient implements HttpClient {
// If all connections where evicted cancel the eviction timer.
if (_openSockets.isEmpty) _cancelEvictionTimer();
}
_evictionTimer = new Timer.repeating(10000, _handleEviction);
_evictionTimer = new Timer.repeating(const Duration(seconds: 10),
_handleEviction);
}
// Return connection.

View file

@ -125,7 +125,7 @@ class _HttpSessionManager {
session._next = session._prev = null;
}
void _timerTimeout(_) {
void _timerTimeout() {
_stopTimer(); // Clear timer.
assert(_head != null);
var session = _head;
@ -139,7 +139,8 @@ class _HttpSessionManager {
assert(_timer == null);
if (_head != null) {
int seconds = new DateTime.now().difference(_head.lastSeen).inSeconds;
_timer = new Timer((_sessionTimeout - seconds) * 1000, _timerTimeout);
_timer = new Timer(new Duration(seconds: _sessionTimeout - seconds),
_timerTimeout);
}
}

View file

@ -99,7 +99,7 @@ class _ListOutputStream extends _BaseOutputStream implements ListOutputStream {
}
void _checkScheduleCallbacks() {
void issueDataCallback(Timer timer) {
void issueDataCallback() {
_scheduledDataCallback = null;
if (_clientDataHandler != null) {
_clientDataHandler();
@ -107,7 +107,7 @@ class _ListOutputStream extends _BaseOutputStream implements ListOutputStream {
}
}
void issueNoPendingWriteCallback(Timer timer) {
void issueNoPendingWriteCallback() {
_scheduledNoPendingWriteCallback = null;
if (_clientNoPendingWriteHandler != null &&
!_streamMarkedClosed) {
@ -116,7 +116,7 @@ class _ListOutputStream extends _BaseOutputStream implements ListOutputStream {
}
}
void issueCloseCallback(Timer timer) {
void issueCloseCallback() {
_scheduledCloseCallback = null;
if (_clientCloseHandler != null) _clientCloseHandler();
}
@ -131,18 +131,18 @@ class _ListOutputStream extends _BaseOutputStream implements ListOutputStream {
if (!_bufferList.isEmpty &&
_clientDataHandler != null &&
_scheduledDataCallback == null) {
_scheduledDataCallback = new Timer(0, issueDataCallback);
_scheduledDataCallback = Timer.run(issueDataCallback);
}
if (_clientNoPendingWriteHandler != null &&
_scheduledNoPendingWriteCallback == null &&
_scheduledDataCallback == null) {
_scheduledNoPendingWriteCallback =
new Timer(0, issueNoPendingWriteCallback);
Timer.run(issueNoPendingWriteCallback);
}
} else if (_clientCloseHandler != null) {
_scheduledCloseCallback = new Timer(0, issueCloseCallback);
_scheduledCloseCallback = Timer.run(issueCloseCallback);
_closeCallbackCalled = true;
}
}

View file

@ -589,7 +589,7 @@ class _SecureSocket implements SecureSocket {
scheduledDataEvent = null;
}
} else if (scheduledDataEvent == null) {
scheduledDataEvent = new Timer(0, (_) => _secureDataHandler());
scheduledDataEvent = Timer.run(_secureDataHandler);
}
if (_socketClosedRead) { // An onClose event is pending.
@ -603,7 +603,7 @@ class _SecureSocket implements SecureSocket {
if (_filterReadEmpty) {
// This can't be an else clause: the value of _filterReadEmpty changes.
// This must be asynchronous, because we are in a read or readList call.
new Timer(0, (_) => _secureCloseHandler());
Timer.run(_secureCloseHandler);
}
}
}

View file

@ -102,7 +102,7 @@ class _SocketOutputStream
_socket._closeWrite();
_closed = true;
// Invoke the callback asynchronously.
new Timer(0, (t) {
Timer.run(() {
if (_onClosed != null) _onClosed();
});
}

View file

@ -99,7 +99,7 @@ abstract class _BaseDataInputStream {
}
void _checkScheduleCallbacks() {
void issueDataCallback(Timer timer) {
void issueDataCallback() {
_scheduledDataCallback = null;
if (_clientDataHandler != null) {
_clientDataHandler();
@ -107,7 +107,7 @@ abstract class _BaseDataInputStream {
}
}
void issueCloseCallback(Timer timer) {
void issueCloseCallback() {
_scheduledCloseCallback = null;
_closeCallbackCalled = true;
if (_clientCloseHandler != null) _clientCloseHandler();
@ -119,12 +119,12 @@ abstract class _BaseDataInputStream {
if (!_closeCallbackCalled) {
if (available() > 0) {
if (_scheduledDataCallback == null) {
_scheduledDataCallback = new Timer(0, issueDataCallback);
_scheduledDataCallback = Timer.run(issueDataCallback);
}
} else if (_streamMarkedClosed && _scheduledCloseCallback == null) {
_cancelScheduledDataCallback();
_close();
_scheduledCloseCallback = new Timer(0, issueCloseCallback);
_scheduledCloseCallback = Timer.run(issueCloseCallback);
}
}
}

View file

@ -525,7 +525,7 @@ class _StringInputStream implements StringInputStream {
// TODO(sgjesse): Find a better way of scheduling callbacks from
// the event loop.
void _checkScheduleCallback() {
void issueDataCallback(Timer timer) {
void issueDataCallback() {
_scheduledDataCallback = null;
if (_clientDataHandler != null) {
_clientDataHandler();
@ -533,7 +533,7 @@ class _StringInputStream implements StringInputStream {
}
}
void issueLineCallback(Timer timer) {
void issueLineCallback() {
_scheduledLineCallback = null;
if (_clientLineHandler != null) {
_clientLineHandler();
@ -541,7 +541,7 @@ class _StringInputStream implements StringInputStream {
}
}
void issueCloseCallback(Timer timer) {
void issueCloseCallback() {
_scheduledCloseCallback = null;
if (!_closed) {
if (_clientCloseHandler != null) _clientCloseHandler();
@ -557,7 +557,7 @@ class _StringInputStream implements StringInputStream {
if (_scheduledLineCallback != null) {
_scheduledLineCallback.cancel();
}
_scheduledDataCallback = new Timer(0, issueDataCallback);
_scheduledDataCallback = Timer.run(issueDataCallback);
}
// Schedule line callback if a line is available.
@ -567,14 +567,14 @@ class _StringInputStream implements StringInputStream {
if (_scheduledDataCallback != null) {
_scheduledDataCallback.cancel();
}
_scheduledLineCallback = new Timer(0, issueLineCallback);
_scheduledLineCallback = Timer.run(issueLineCallback);
}
// Schedule close callback if no more data and input is closed.
if (_decoder.isEmpty &&
_inputClosed &&
_scheduledCloseCallback == null) {
_scheduledCloseCallback = new Timer(0, issueCloseCallback);
_scheduledCloseCallback = Timer.run(issueCloseCallback);
}
}
}

View file

@ -453,17 +453,13 @@ class _WebSocketConnectionBase {
if (_closeTimer != null) _closeTimer.cancel();
_socket.close();
};
_closeTimer = new Timer(5000, (t) {
_socket.close();
});
_closeTimer = new Timer(const Duration(seconds: 5), _socket.close);
} else {
// Half close the socket and expect a close frame in response
// before closing the socket. If a close frame does not arrive
// within a reasonable amount of time just close the socket.
_socket.outputStream.close();
_closeTimer = new Timer(5000, (t) {
_socket.close();
});
_closeTimer = new Timer(const Duration(seconds: 5), _socket.close);
}
_closeSent = true;
}

View file

@ -7,16 +7,17 @@ import 'dart:isolate';
import 'async_helper.dart';
void test(void onDone(bool success)) {
Duration ms = const Duration(milliseconds: 1);
int expected = 4;
void timerCallback(timer) {
void timerCallback() {
if (--expected == 0) onDone(false);
}
new Timer(0, timerCallback);
new Timer(10, timerCallback);
new Timer(100, timerCallback);
new Timer(1000, timerCallback);
new Timer(ms * 0, timerCallback);
new Timer(ms * 10, timerCallback);
new Timer(ms * 100, timerCallback);
new Timer(ms * 1000, timerCallback);
}
main() {

View file

@ -8,16 +8,17 @@ import 'dart:isolate';
import 'async_helper.dart';
void test(void onDone(bool success)) {
Duration ms = const Duration(milliseconds: 1);
int expected = 4;
void timerCallback(timer) {
void timerCallback() {
if (--expected == 0) onDone(true);
}
new Timer(0, timerCallback);
new Timer(10, timerCallback);
new Timer(100, timerCallback);
new Timer(1000, timerCallback);
new Timer(ms * 0, timerCallback);
new Timer(ms * 10, timerCallback);
new Timer(ms * 100, timerCallback);
new Timer(ms * 1000, timerCallback);
}
main() {

View file

@ -45,7 +45,8 @@ void main() {
originalTest.main();
test('dromaeo runs', () {
new Timer.repeating(500, expectAsyncUntil1((timer) {
new Timer.repeating(new Duration(milliseconds: 500),
expectAsyncUntil1((timer) {
if (document.query('.alldone') != null) {
timer.cancel();
isDone = true;

View file

@ -7,44 +7,44 @@ library multiple_timer_test;
import 'dart:async';
import '../../pkg/unittest/lib/unittest.dart';
const int TIMEOUT1 = 1000;
const int TIMEOUT2 = 2000;
const int TIMEOUT3 = 500;
const int TIMEOUT4 = 1500;
const Duration TIMEOUT1 = const Duration(seconds: 1);
const Duration TIMEOUT2 = const Duration(seconds: 2);
const Duration TIMEOUT3 = const Duration(milliseconds: 500);
const Duration TIMEOUT4 = const Duration(milliseconds: 1500);
main() {
test("multiple timer test", () {
int _startTime1;
int _startTime2;
int _startTime3;
int _startTime4;
Stopwatch _stopwatch1 = new Stopwatch();
Stopwatch _stopwatch2 = new Stopwatch();
Stopwatch _stopwatch3 = new Stopwatch();
Stopwatch _stopwatch4 = new Stopwatch();
List<int> _order;
int _message;
void timeoutHandler1(Timer timer) {
int endTime = (new DateTime.now()).millisecondsSinceEpoch;
expect(endTime - _startTime1, greaterThanOrEqualTo(TIMEOUT1));
void timeoutHandler1() {
expect(_stopwatch1.elapsedMilliseconds,
greaterThanOrEqualTo(TIMEOUT1.inMilliseconds));
expect(_order[_message], 0);
_message++;
}
void timeoutHandler2(Timer timer) {
int endTime = (new DateTime.now()).millisecondsSinceEpoch;
expect(endTime - _startTime2, greaterThanOrEqualTo(TIMEOUT2));
void timeoutHandler2() {
expect(_stopwatch2.elapsedMilliseconds,
greaterThanOrEqualTo(TIMEOUT2.inMilliseconds));
expect(_order[_message], 1);
_message++;
}
void timeoutHandler3(Timer timer) {
int endTime = (new DateTime.now()).millisecondsSinceEpoch;
expect(endTime - _startTime3, greaterThanOrEqualTo(TIMEOUT3));
void timeoutHandler3() {
expect(_stopwatch3.elapsedMilliseconds,
greaterThanOrEqualTo(TIMEOUT3.inMilliseconds));
expect(_order[_message], 2);
_message++;
}
void timeoutHandler4(Timer timer) {
int endTime = (new DateTime.now()).millisecondsSinceEpoch;
expect(endTime - _startTime4, greaterThanOrEqualTo(TIMEOUT4));
void timeoutHandler4() {
expect(_stopwatch4.elapsedMilliseconds,
greaterThanOrEqualTo(TIMEOUT4.inMilliseconds));
expect(_order[_message], 3);
_message++;
}
@ -56,13 +56,13 @@ main() {
_order[3] = 1;
_message = 0;
_startTime1 = (new DateTime.now()).millisecondsSinceEpoch;
new Timer(TIMEOUT1, expectAsync1(timeoutHandler1));
_startTime2 = (new DateTime.now()).millisecondsSinceEpoch;
new Timer(TIMEOUT2, expectAsync1(timeoutHandler2));
_startTime3 = (new DateTime.now()).millisecondsSinceEpoch;
new Timer(TIMEOUT3, expectAsync1(timeoutHandler3));
_startTime4 = (new DateTime.now()).millisecondsSinceEpoch;
new Timer(TIMEOUT4, expectAsync1(timeoutHandler4));
_stopwatch1.start();
new Timer(TIMEOUT1, expectAsync0(timeoutHandler1));
_stopwatch2.start();
new Timer(TIMEOUT2, expectAsync0(timeoutHandler2));
_stopwatch3.start();
new Timer(TIMEOUT3, expectAsync0(timeoutHandler3));
_stopwatch4.start();
new Timer(TIMEOUT4, expectAsync0(timeoutHandler4));
});
}

View file

@ -12,15 +12,17 @@ main() {
var canceleeTimer;
var cancelerTimer;
void unreachable(Timer timer) {
void unreachable() {
fail("A canceled timeout handler should be unreachable.");
}
void handler(Timer timer) {
void handler() {
canceleeTimer.cancel();
}
cancelerTimer = new Timer(1, expectAsync1(handler));
canceleeTimer = new Timer(1000, expectAsync1(unreachable, count: 0));
cancelerTimer = new Timer(const Duration(milliseconds: 1),
expectAsync0(handler));
canceleeTimer = new Timer(const Duration(milliseconds: 1000),
expectAsync0(unreachable, count: 0));
});
}

View file

@ -16,6 +16,7 @@ main() {
cancelTimer.cancel();
}
cancelTimer = new Timer.repeating(1, expectAsync1(cancelHandler));
cancelTimer = new Timer.repeating(const Duration(milliseconds: 1),
expectAsync1(cancelHandler));
});
}

View file

@ -9,15 +9,16 @@ import 'dart:isolate';
import '../../pkg/unittest/lib/unittest.dart';
main() {
final ms = const Duration(milliseconds: 1);
test("simple timer", () {
Timer cancelTimer;
int repeatTimer;
void unreachable(Timer timer) {
void unreachable() {
fail("should not be reached");
}
void handler(Timer timer) {
void handler() {
cancelTimer.cancel();
}
@ -27,17 +28,17 @@ main() {
expect(repeatTimer, 1);
}
cancelTimer = new Timer(1000, expectAsync1(unreachable, count: 0));
cancelTimer = new Timer(ms * 1000, expectAsync0(unreachable, count: 0));
cancelTimer.cancel();
new Timer(1000, expectAsync1(handler));
cancelTimer = new Timer(2000, expectAsync1(unreachable, count: 0));
new Timer(ms * 1000, expectAsync0(handler));
cancelTimer = new Timer(ms * 2000, expectAsync0(unreachable, count: 0));
repeatTimer = 0;
new Timer.repeating(1500, expectAsync1(repeatHandler));
new Timer.repeating(ms * 1500, expectAsync1(repeatHandler));
});
test("cancel timer with same time", () {
var t2;
var t1 = new Timer(0, expectAsync1((t) => t2.cancel()));
t2 = new Timer(0, expectAsync1((t) => t1.cancel(), count: 0));
var t1 = Timer.run(expectAsync0(() => t2.cancel()));
t2 = Timer.run(expectAsync0(t1.cancel, count: 0));
});
}

View file

@ -8,11 +8,11 @@ import 'dart:isolate';
import 'dart:async';
import '../../pkg/unittest/lib/unittest.dart';
const int TIMEOUT = 100;
const Duration TIMEOUT = const Duration(milliseconds: 100);
createTimer() {
port.receive((msg, replyTo) {
new Timer(TIMEOUT, (_) {
new Timer(TIMEOUT, () {
replyTo.send("timer_fired");
});
});
@ -22,14 +22,14 @@ main() {
test("timer in isolate", () {
int startTime;
int endTime;
port.receive(expectAsync2((msg, _) {
expect("timer_fired", msg);
int endTime = (new DateTime.now()).millisecondsSinceEpoch;
expect(endTime - startTime, greaterThanOrEqualTo(TIMEOUT));
port.close();
}));
startTime = (new DateTime.now()).millisecondsSinceEpoch;
var sendPort = spawnFunction(createTimer);
sendPort.send("sendPort", port.toSendPort());

View file

@ -7,16 +7,17 @@ library timerNotAvailable;
import 'dart:async';
main() {
final ms = const Duration(milliseconds: 1);
bool failed = false;
try {
new Timer(5, (_) { });
new Timer(ms * 5, () { });
} on UnsupportedError catch (e) {
failed = true;
}
Expect.isTrue(failed);
failed = false;
try {
var t = new Timer.repeating(10, (_) { });
var t = new Timer.repeating(ms * 10, (_) { });
t.cancel();
} on UnsupportedError catch (e) {
failed = true;

View file

@ -7,7 +7,7 @@ library timer_repeat_test;
import 'dart:async';
import '../../pkg/unittest/lib/unittest.dart';
const int TIMEOUT = 500;
const Duration TIMEOUT = const Duration(milliseconds: 500);
const int ITERATIONS = 5;
Timer timer;

View file

@ -15,14 +15,15 @@ int startTime;
int timeout;
int iteration;
void timeoutHandler(Timer timer) {
void timeoutHandler() {
int endTime = (new DateTime.now()).millisecondsSinceEpoch;
expect(endTime - startTime, greaterThanOrEqualTo(timeout));
if (iteration < ITERATIONS) {
iteration++;
timeout = timeout - DECREASE;
Duration duration = new Duration(milliseconds: timeout);
startTime = (new DateTime.now()).millisecondsSinceEpoch;
new Timer(timeout, expectAsync1(timeoutHandler));
new Timer(duration, expectAsync0(timeoutHandler));
}
}
@ -30,7 +31,8 @@ main() {
test("timeout test", () {
iteration = 0;
timeout = STARTTIMEOUT;
Duration duration = new Duration(milliseconds: timeout);
startTime = (new DateTime.now()).millisecondsSinceEpoch;
new Timer(timeout, expectAsync1(timeoutHandler));
new Timer(duration, expectAsync0(timeoutHandler));
});
}

View file

@ -10,7 +10,7 @@ import "dart:async";
class X {
Function onX;
X() { new Timer(0, (_) => onX(new Y())); }
X() { Timer.run(() => onX(new Y())); }
}
class Y {
@ -22,7 +22,7 @@ class Y {
heavyMemory = new List(10*1024*1024);
// Terminate the test if we allocated enough memory without running out.
if (count++ > 100) return;
new Timer(0, (_) => onY());
Timer.run(() => onY());
}
}

View file

@ -7,6 +7,8 @@ library future_test;
import 'dart:async';
import 'dart:isolate';
const Duration MS = const Duration(milliseconds: 1);
testImmediate() {
final future = new Future<String>.immediate("42");
var port = new ReceivePort();
@ -357,7 +359,7 @@ testFutureWhenCompletePreValue() {
var completer = new Completer();
Future future = completer.future;
completer.complete(42);
new Timer(0, () {
Timer.run(() {
Future later = future.whenComplete(countDown);
later.then((v) {
Expect.equals(42, v);
@ -367,6 +369,7 @@ testFutureWhenCompletePreValue() {
}
testFutureWhenValueFutureValue() {
var port = new ReceivePort();
int counter = 3;
countDown(int expect) {
@ -377,7 +380,7 @@ testFutureWhenValueFutureValue() {
completer.future.whenComplete(() {
countDown(3);
var completer2 = new Completer();
new Timer(10, (_) {
new Timer(MS * 10, () {
countDown(2);
completer2.complete(37);
});
@ -401,7 +404,7 @@ testFutureWhenValueFutureError() {
completer.future.whenComplete(() {
countDown(3);
var completer2 = new Completer();
new Timer(10, (_) {
new Timer(MS * 10, () {
countDown(2);
completer2.completeError("Fail");
});
@ -427,7 +430,7 @@ testFutureWhenErrorFutureValue() {
completer.future.whenComplete(() {
countDown(3);
var completer2 = new Completer();
new Timer(10, (_) {
new Timer(MS * 10, () {
countDown(2);
completer2.complete(37);
});
@ -453,7 +456,7 @@ testFutureWhenErrorFutureError() {
completer.future.whenComplete(() {
countDown(3);
var completer2 = new Completer();
new Timer(10, (_) {
new Timer(MS * 10, () {
countDown(2);
completer2.completeError("Fail");
});

View file

@ -35,7 +35,8 @@ class SlowConsumer extends StreamConsumer {
subscription.pause();
usedBufferSize = 0;
int ms = data.length * 1000 ~/ bytesPerSecond;
new Timer(ms, (_) {
Duration duration = new Duration(milliseconds: ms);
new Timer(duration, () {
for (int i = 0; i < currentBufferedDataLength; i++) {
bufferedData[i] = null;
}
@ -57,7 +58,7 @@ class DataProvider {
DataProvider(int this.bytesPerSecond, int this.targetCount, this.chunkSize) {
controller = new StreamController(onPauseStateChange: onPauseStateChange);
new Timer(0, (_) => send());
Timer.run(send);
}
Stream get stream => controller.stream;
@ -76,7 +77,8 @@ class DataProvider {
}
controller.add(new List.fixedLength(listSize));
int ms = listSize * 1000 ~/ bytesPerSecond;
if (!controller.isPaused) new Timer(ms, (_) => send());
Duration duration = new Duration(milliseconds: ms);
if (!controller.isPaused) new Timer(duration, send);
}
onPauseStateChange() {

View file

@ -35,7 +35,8 @@ class SlowConsumer extends StreamConsumer {
subscription.pause();
usedBufferSize = 0;
int ms = data.length * 1000 ~/ bytesPerSecond;
new Timer(ms, (_) {
Duration duration = new Duration(milliseconds: ms);
new Timer(duration, () {
for (int i = 0; i < currentBufferedDataLength; i++) {
bufferedData[i] = null;
}

View file

@ -50,7 +50,7 @@ class DataProvider {
DataProvider(int this.bytesPerSecond, int this.targetCount, this.chunkSize) {
controller = new StreamController(onPauseStateChange: onPauseStateChange);
new Timer(0, (_) => send());
Timer.run(send);
}
Stream get stream => controller.stream;
@ -69,7 +69,8 @@ class DataProvider {
}
controller.add(new List.fixedLength(listSize));
int ms = listSize * 1000 ~/ bytesPerSecond;
if (!controller.isPaused) new Timer(ms, (_) => send());
Duration duration = new Duration(milliseconds: ms);
if (!controller.isPaused) new Timer(duration, send);
}
onPauseStateChange() {

View file

@ -168,7 +168,7 @@ void testBasicAuthenticateCallback() {
String password = url.path.substring(1, 6);
if (passwordChanged) password = "${password}1";
Completer completer = new Completer();
new Timer(10, (_) {
new Timer(const Duration(milliseconds: 10), () {
client.addCredentials(
url, realm, new HttpClientBasicCredentials(username, password));
completer.complete(true);

View file

@ -51,7 +51,7 @@ void testStreamResponse() {
};
server.listen("127.0.0.1", 0, backlog: 5);
server.defaultRequestHandler = (var request, var response) {
timer = new Timer.repeating(10, (_) {
timer = new Timer.repeating(new Duration(milliseconds: 10), (_) {
DateTime now = new DateTime.now();
try {
response.outputStream.writeString(

View file

@ -13,7 +13,7 @@ class Server {
port = server.port;
server.defaultRequestHandler =
(HttpRequest request, HttpResponse response) {
new Timer(0, (timer) => server.close());
Timer.run(server.close);
};
server.onError = (e) {
Expect.fail("No server errors expected: $e");

View file

@ -116,7 +116,7 @@ void test4() {
server.listen("127.0.0.1", 0);
server.defaultRequestHandler = (var request, var response) {
request.inputStream.onClosed = () {
new Timer.repeating(100, (timer) {
new Timer.repeating(new Duration(milliseconds: 100), (timer) {
if (server.connectionsInfo().total == 0) {
server.close();
timer.cancel();
@ -157,7 +157,7 @@ void test5(int totalConnections) {
conn.onError = (e) => Expect.isTrue(e is HttpException);
}
bool clientClosed = false;
new Timer.repeating(100, (timer) {
new Timer.repeating(new Duration(milliseconds: 100), (timer) {
if (!clientClosed) {
if (server.connectionsInfo().total == totalConnections) {
clientClosed = true;

View file

@ -126,11 +126,11 @@ void testListOutputStream4() {
stream.onData = onData;
stream.onClosed = onClosed;
new Timer(0, (_) {
Timer.run(() {
result.add(1);
stream.write([2]);
new Timer(0, (_) {
Timer.run(() {
result.add(3);
stream.write([4]);
stream.close();

View file

@ -123,11 +123,11 @@ void main() {
keepAlive.close();
};
int delay = 0;
int delay_between_connections = 300; // Milliseconds.
Duration delay = const Duration(milliseconds: 0);
Duration delay_between_connections = const Duration(milliseconds: 300);
for (var x in CLIENT_NAMES) {
new Timer(delay, (_) {
new Timer(delay, () {
new SecureTestClient(port, x);
});
delay += delay_between_connections;

View file

@ -200,7 +200,7 @@ void main() {
createDart: true,
createSnapshot: true);
void touchFilesAndRunTests(Timer unused) {
void touchFilesAndRunTests() {
fs_notUpToDate_snapshot.touchFile(fs_notUpToDate_snapshot.testSnapshot);
fs_notUpToDate_dart.touchFile(fs_notUpToDate_dart.testDart);
fs_upToDate.touchFile(fs_upToDate.testJs);
@ -222,5 +222,5 @@ void main() {
}
// We need to wait some time to make sure that the files we 'touch' get a
// bigger timestamp than the old ones
new Timer(1000, touchFilesAndRunTests);
new Timer(new Duration(seconds: 1), touchFilesAndRunTests);
}

View file

@ -33,13 +33,13 @@ class SocketClose {
void proceed() {
if (_iterations < ITERATIONS) {
new Timer(0, sendData);
Timer.run(sendData);
} else {
shutdown();
}
}
void sendData(Timer timer) {
void sendData() {
void dataHandler() {
switch (_mode) {
@ -296,7 +296,7 @@ class SocketCloseServer {
Expect.fail("Server socket error");
}
waitForResult(Timer timer) {
waitForResult() {
// Make sure all iterations have been run. In multiple of these
// scenarios it is possible to get the SERVERSHUTDOWN message
// before we have received the last close event on the
@ -332,7 +332,7 @@ class SocketCloseServer {
port.close();
_donePort.send(null);
} else {
new Timer(100, waitForResult);
new Timer(new Duration(milliseconds: 100), waitForResult);
}
}
@ -354,7 +354,7 @@ class SocketCloseServer {
_server.onError = errorHandlerServer;
replyTo.send(_server.port, null);
} else {
new Timer(0, waitForResult);
Timer.run(waitForResult);
}
}

View file

@ -33,13 +33,13 @@ class SocketClose {
void proceed() {
if (_iterations < ITERATIONS) {
new Timer(0, sendData);
Timer.run(sendData);
} else {
shutdown();
}
}
void sendData(Timer timer) {
void sendData() {
void dataHandler() {
switch (_mode) {
@ -317,7 +317,7 @@ class SocketCloseServer {
Expect.fail("Server socket error");
}
waitForResult(Timer timer) {
waitForResult() {
// Make sure all iterations have been run. In multiple of these
// scenarios it is possible to get the SERVERSHUTDOWN message
// before we have received the last close event on the
@ -356,7 +356,7 @@ class SocketCloseServer {
port.close();
_donePort.send(null);
} else {
new Timer(100, waitForResult);
new Timer(new Duration(milliseconds: 100), waitForResult);
}
}
@ -378,7 +378,7 @@ class SocketCloseServer {
_server.onError = errorHandlerServer;
replyTo.send(_server.port, null);
} else {
new Timer(0, waitForResult);
Timer.run(waitForResult);
}
}

View file

@ -17,5 +17,5 @@ main() {
// Make sure the exception is thrown out to the event handler from C++ code.
// The harness expects the string "ball" to be thrown and the process to
// end with an unhandled exception.
new Timer(0, (_) => Cat.throwMeTheBall("ball"));
Timer.run(() => Cat.throwMeTheBall("ball"));
}

View file

@ -114,7 +114,7 @@ void main() {
break;
case 'timeout':
// Run for 10 seconds, then exit. This tests a 2 second timeout.
new Timer(10 * 1000, (t){ });
new Timer(new Duration(seconds: 10), (){ });
break;
default:
throw "Unknown option ${arguments[0]} passed to test_runner_test";

View file

@ -702,7 +702,7 @@ Future _doProcess(Function fn, String executable, List<String> args, workingDir,
Future timeout(Future input, int milliseconds, String description) {
bool completed = false;
var completer = new Completer();
var timer = new Timer(milliseconds, (_) {
var timer = new Timer(new Duration(milliseconds: milliseconds), () {
completed = true;
completer.completeError(new TimeoutException(
'Timed out while $description.'));

View file

@ -158,7 +158,7 @@ Future defer(callback()) {
/// Returns a [Future] that completes in [milliseconds].
Future sleep(int milliseconds) {
var completer = new Completer();
new Timer(milliseconds, (_) => completer.complete());
new Timer(new Duration(milliseconds: milliseconds), completer.complete);
return completer.future;
}

View file

@ -68,7 +68,7 @@ Future _processHelper(String command, List<String> args,
processFuture.then((process) {
_procs[procId] = process;
timer = new Timer(1000 * timeout, (t) {
timer = new Timer(new Duration(seconds: timeout), () {
timer = null;
process.kill();
});

View file

@ -528,7 +528,7 @@ class MockVersionlessSource extends Source {
Future fakeAsync(callback()) {
var completer = new Completer();
new Timer(0, (_) {
Timer.run(() {
completer.complete(callback());
});

View file

@ -420,7 +420,7 @@ class CPSBenchmarkRunner extends Runner {
}
static void _addToEventQueue(Function action) {
new Timer(0, _(Timer t) => action());
Timer.run(action);
}
}