aboutsummaryrefslogtreecommitdiffstats
path: root/staging_vespalib/src/vespa/vespalib/util/scheduledexecutor.cpp
blob: d9b4feda293f4d14b6e777c837a0538a32076cd3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "scheduledexecutor.h"
#include <vespa/fnet/scheduler.h>
#include <vespa/fnet/task.h>
#include <vespa/fnet/transport.h>

namespace vespalib {

typedef vespalib::Executor::Task Task;

class TimerTask : public FNET_Task
{
private:
    TimerTask(const TimerTask &);
    TimerTask&operator=(const TimerTask &);

    FNET_Scheduler *_scheduler;
    Task::UP _task;
    duration _interval;
public:
    TimerTask(FNET_Scheduler *scheduler, Task::UP task, duration interval)
        : FNET_Task(scheduler),
          _task(std::move(task)),
          _interval(interval)
    { }

    ~TimerTask() {
        Kill();
    }

    void PerformTask() override {
        _task->run();
        Schedule(to_s(_interval));
    }
};

ScheduledExecutor::ScheduledExecutor()
    : _threadPool(128 * 1024),
      _transport(new FNET_Transport()),
      _lock(),
      _taskList()
{
    _transport->Start(&_threadPool);
}

ScheduledExecutor::~ScheduledExecutor()
{
    vespalib::LockGuard guard(_lock);
    _transport->ShutDown(true);
    _threadPool.Close();
    _taskList.clear();
}


void
ScheduledExecutor::scheduleAtFixedRate(vespalib::Executor::Task::UP task, duration delay, duration interval)
{
    vespalib::LockGuard guard(_lock);
    TimerTaskPtr tTask(new TimerTask(_transport->GetScheduler(), std::move(task), interval));
    _taskList.push_back(std::move(tTask));
    _taskList.back()->Schedule(to_s(delay));
}

void
ScheduledExecutor::reset()
{
    vespalib::LockGuard guard(_lock);
    _transport->ShutDown(true);
    _taskList.clear();
    _transport.reset(new FNET_Transport());
    _transport->Start(&_threadPool);
}

}