1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef NET_QUIC_QUIC_ALARM_H_
6#define NET_QUIC_QUIC_ALARM_H_
7
8#include "base/memory/scoped_ptr.h"
9#include "net/base/net_export.h"
10#include "net/quic/quic_time.h"
11
12namespace net {
13
14// Abstract class which represents an alarm which will go off at a
15// scheduled time, and execute the |OnAlarm| method of the delegate.
16// An alarm may be cancelled, in which case it may or may not be
17// removed from the underlying scheduling system, but in either case
18// the task will not be executed.
19class NET_EXPORT_PRIVATE QuicAlarm {
20 public:
21  class NET_EXPORT_PRIVATE Delegate {
22   public:
23    virtual ~Delegate() {}
24
25    // Invoked when the alarm fires.  If the return value is not
26    // infinite, then the alarm will be rescheduled at the
27    // specified time.
28    virtual QuicTime OnAlarm() = 0;
29  };
30
31  explicit QuicAlarm(Delegate* delegate);
32  virtual ~QuicAlarm();
33
34  // Sets the alarm to fire at |deadline|.  Must not be called while
35  // the alarm is set.  To reschedule an alarm, call Cancel() first,
36  // then Set().
37  void Set(QuicTime deadline);
38
39  // Cancels the alarm.  May be called repeatedly.  Does not
40  // guarantee that the underlying scheduling system will remove
41  // the alarm's associated task, but guarantees that the
42  // delegates OnAlarm method will not be called.
43  void Cancel();
44
45  // Cancels and sets the alarm if the |deadline| is farther from the current
46  // deadline than |granularity|, and otherwise does nothing.  If |deadline| is
47  // not initialized, the alarm is cancelled.
48  void Update(QuicTime deadline, QuicTime::Delta granularity);
49
50  bool IsSet() const;
51
52  QuicTime deadline() const { return deadline_; }
53
54 protected:
55  // Subclasses implement this method to perform the platform-specific
56  // scheduling of the alarm.  Is called from Set() or Fire(), after the
57  // deadline has been updated.
58  virtual void SetImpl() = 0;
59
60  // Subclasses implement this method to perform the platform-specific
61  // cancelation of the alarm.
62  virtual void CancelImpl() = 0;
63
64  // Called by subclasses when the alarm fires.  Invokes the
65  // delegates |OnAlarm| if a delegate is set, and if the deadline
66  // has been exceeded.  Implementations which do not remove the
67  // alarm from the underlying scheduler on Cancel() may need to handle
68  // the situation where the task executes before the deadline has been
69  // reached, in which case they need to reschedule the task and must not
70  // call invoke this method.
71  void Fire();
72
73 private:
74  scoped_ptr<Delegate> delegate_;
75  QuicTime deadline_;
76
77  DISALLOW_COPY_AND_ASSIGN(QuicAlarm);
78};
79
80}  // namespace net
81
82#endif  // NET_QUIC_QUIC_ALARM_H_
83