chromium/third_party/openscreen/src/util/alarm.h

// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef UTIL_ALARM_H_
#define UTIL_ALARM_H_

#include <utility>

#include "platform/api/task_runner.h"
#include "platform/api/time.h"

namespace openscreen {

// A simple mechanism for running one Task in the future, but also allow for
// canceling the Task before it runs and/or re-scheduling a replacement Task to
// run at a different time. This mechanism is also scoped to its lifetime: if an
// Alarm is destroyed while it is scheduled, the Task is automatically canceled.
// It is safe for the client's Task to make re-entrant calls into all Alarm
// methods.
//
// Example use case: When using a TaskRunner, an object can safely schedule a
// callback into one of its instance methods (without the possibility of the
// Task executing after the object is destroyed).
//
// Design: In order to support efficient, arbitrary canceling and re-scheduling
// by the client, the Alarm posts a cancelable functor to the TaskRunner which,
// when invoked, then checks to see whether the Alarm instance still exists and,
// if so, calls its TryInvoke() method. The TryInvoke() method then determines:
// a) whether the invocation time of the client's Task has changed; and b)
// whether the Alarm was canceled in the meantime. From this, it either: a) does
// nothing; b) re-posts a new cancelable functor to the TaskRunner, to try
// running the client's Task later; or c) runs the client's Task.
class Alarm {};

}  // namespace openscreen

#endif  // UTIL_ALARM_H_