|
|
|
|
|
|
|
The `TaskScheduler` is one of the most used and useful components provided by `skyward-boardcore` (`src/shared/scheduler`).
|
|
|
|
|
|
|
|
It is an [active object](Active-Object) that allows to run periodic tasks (functions) with user-selectable period.
|
|
|
|
This is very useful in order for example to perform the sampling of all the required sensors, but also to run control algorithms that have to be periodically updated.
|
|
|
|
One of the best advantages to use such component is that all the functions given to the scheduler are executed in the same thread.
|
|
|
|
|
|
|
|
## Adding Tasks
|
|
|
|
The interface for adding a new task is pretty simple:
|
|
|
|
```cpp
|
|
|
|
void add(std::function<void()> func, uint32_t intervalMs, uint8_t id, int64_t start = miosix::getTick());
|
|
|
|
```
|
|
|
|
Where the parameters are: the function to be periodically executed, the task period in milliseconds, an identifier for the task and the start time (by default set to the current system time).
|
|
|
|
|
|
|
|
> :warning: **Tasks in the tasks scheduler are meant to be added at inizialization. This means that all the tasks have to be added to the scheduler before the _start()_ method is called (which will start the thread execution).**
|
|
|
|
|
|
|
|
A method for adding tasks that have to be executed only once also exists and is called `addOnce(...)`. Instead of an execution period, it allows to specify a delay after which the task will be executed.
|
|
|
|
|
|
|
|
## Example
|
|
|
|
The following example creates a `TaskScheduler`, adds to it a period task with period 1 second (1000 milliseconds).
|
|
|
|
```cpp
|
|
|
|
#include "Common.h"
|
|
|
|
#include "scheduler/TaskScheduler.h"
|
|
|
|
|
|
|
|
using namespace miosix;
|
|
|
|
|
|
|
|
void task()
|
|
|
|
{
|
|
|
|
static long long last_tick = getTick();
|
|
|
|
|
|
|
|
printf("Task executed at %d\n", (int)(getTick() - last_tick));
|
|
|
|
}
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
TaskScheduler scheduler;
|
|
|
|
|
|
|
|
TaskScheduler::function_t f{&task};
|
|
|
|
// add task with period 1 second and id 1
|
|
|
|
scheduler.add(f, 1000, 1);
|
|
|
|
|
|
|
|
// start the active object thread
|
|
|
|
scheduler.start();
|
|
|
|
|
|
|
|
Thread::sleep(10000);
|
|
|
|
|
|
|
|
scheduler.stop();
|
|
|
|
printf("End\n");
|
|
|
|
|
|
|
|
for(;;)
|
|
|
|
{
|
|
|
|
Thread::sleep(5000);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
``` |
|
|
\ No newline at end of file |