The TaskScheduler
is one of the most used and useful components provided by skyward-boardcore
(src/shared/scheduler
).
It is an 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 of using such a 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:
size_t addTask(function_t function, uint32_t period, Policy policy = Policy::SKIP, int64_t startTick = miosix::getTick());
Where function_t
is an std::function<void()>
.
The parameters are: the function to be periodically executed, the task period in milliseconds, the policy and the start time (by default set to the current system time). Note that the unique task ID is auto generated.
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).
#include "miosix.h"
#include "scheduler/TaskScheduler.h"
using namespace miosix;
using namespace Boardcore;
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.addTask(f, 1000, TaskScheduler::Policy::ONE_SHOT, miosix::getTick());
// start the active object thread
scheduler.start();
Thread::sleep(10000);
scheduler.stop();
printf("End\n");
for(;;)
{
Thread::sleep(5000);
}
}