#ifndef CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_OP_SCHEDULER_H_
#define CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_OP_SCHEDULER_H_
#include <map>
#include <vector>
#include "base/containers/queue.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
#include "content/common/content_export.h"
namespace content {
class CONTENT_EXPORT BackgroundSyncOpScheduler {
public:
explicit BackgroundSyncOpScheduler(
scoped_refptr<base::SequencedTaskRunner> task_runner);
BackgroundSyncOpScheduler(const BackgroundSyncOpScheduler&) = delete;
BackgroundSyncOpScheduler& operator=(const BackgroundSyncOpScheduler&) =
delete;
virtual ~BackgroundSyncOpScheduler();
void ScheduleOperation(base::OnceClosure closure);
void CompleteOperationAndRunNext();
bool ScheduledOperations() const;
template <typename... Args>
base::OnceCallback<void(Args...)> WrapCallbackToRunNext(
base::OnceCallback<void(Args...)> callback) {
return base::BindOnce(
&BackgroundSyncOpScheduler::RunNextContinuation<Args...>,
weak_ptr_factory_.GetWeakPtr(), std::move(callback));
}
protected:
virtual void DoneStartingAvailableOperations() {}
private:
class Operation;
void MaybeRunOperation();
template <typename... Args>
void RunNextContinuation(base::OnceCallback<void(Args...)> callback,
Args... args) {
base::WeakPtr<BackgroundSyncOpScheduler> scheduler =
weak_ptr_factory_.GetWeakPtr();
std::move(callback).Run(std::forward<Args>(args)...);
if (scheduler)
CompleteOperationAndRunNext();
}
scoped_refptr<base::SequencedTaskRunner> task_runner_;
base::queue<std::unique_ptr<Operation>> pending_operations_;
std::unique_ptr<Operation> running_operation_;
SEQUENCE_CHECKER(sequence_checker_);
base::WeakPtrFactory<BackgroundSyncOpScheduler> weak_ptr_factory_{this};
};
}
#endif