Evgenii Legotckoi
Evgenii LegotckoiDec. 28, 2018, 8:09 p.m.

Boost - performing periodic tasks using boost::thread

I propose to write a small console program that will perform one task at regular intervals.

For example, the program starts and makes 10 samples within 10 seconds, while the program will display information about the number of the countdown in the console.

The program will work as follows.

Выполнение периодический задачи в консольном приложении


Project structure

The project uses the CMake build system, so the project structure will be as follows..

PeriodicTask project structure

CMakeLists.txt

Here is the standard CMake config for building the project.

cmake_minimum_required (VERSION 3.8)

project(Periodic)

set(CMAKE_CXX_STANDARD 17)
set(Boost_USE_STATIC_LIBS ON)

find_package(Boost 1.68 REQUIRED COMPONENTS thread)

set(SOURCE_FILES
        Periodic/main.cpp
        Periodic/PeriodicTask.cpp)

SET(HEADER_FILES
        Periodic/PeriodicTask.h)

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(Periodic ${SOURCE_FILES} ${HEADER_FILES})
    target_link_libraries(Periodic ${Boost_LIBRARIES})
endif()

PeriodicTask.h

Header file of the periodic task.

In the simplest case, to create a class of a periodic problem, we need:

  • a trigger period
  • object std::function to store the task
  • variable bool to stop and start the task. In this example, we will not stop the task, but if we add run / stop methods, then it is quite possible to implement it.
  • boost::thread - a thread without which this functionality cannot be implemented
#pragma once

#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <functional>
#include <atomic>

class PeriodicTask
{
public:
    explicit PeriodicTask(const boost::chrono::milliseconds &period, const std::function<void()> &func);

    virtual ~PeriodicTask();

private:
    boost::chrono::milliseconds m_period;   // Task period
    std::function<void()> m_func;           // The function that will perform the periodic task
    std::atomic<bool> m_running;            // A variable that indicates that the task is running, with the help of it you can stop the task in the future
    boost::thread m_thread;                 // Task thread
};

PeriodicTask.cpp

#include "PeriodicTask.h"

PeriodicTask::PeriodicTask(const boost::chrono::milliseconds &period, const std::function<void()> &func) :
    m_period(period),
    m_func(func),
    m_running(true)
{
    // Create a stream object to perform a periodic task.
    m_thread = boost::thread([this]
    {
        while (m_running)
        {
            // To perform a task with a specific period, immerse the stream in a dream after each task execution.
            boost::this_thread::sleep_for(m_period);
            if (m_running)
            {
                // perform the task
                m_func();
            }
        }
    });
}

PeriodicTask::~PeriodicTask()
{
    // When destroying an object with a periodic task
    m_running = false;
    // interrupt the flow, otherwise the program will not release system resources until the flow comes out of sleep
    // this is critical if the trigger period of the task is measured in tens of seconds and more
    m_thread.interrupt();
    m_thread.join();
}

main.cpp

File with main function. When we create an object of a periodic task, we put the lambda function in it as the task, as the easiest way to indicate what work needs to be done.

#include "PeriodicTask.h" // We connect the class header file to perform periodic tasks.

#include <iostream>

int main(int argc, const char* argv[])
{
    std::cout << "Start program" << std::endl;
    int count = 0;
    // Create a periodic task with a period of 1 second
    PeriodicTask p(boost::chrono::seconds{ 1 }, [&count]() {
        // Display the counter and increment it by one.
        std::cout << count++ << std::endl;
    });

    // Stop the main program flow for 10 seconds so that the periodic task can work 10 times.
    boost::this_thread::sleep_for(boost::chrono::seconds{ 10 });
    std::cout << "End program" << std::endl;
    return 0;
}

Coclusion

As a conclusion I attach the archive with the project.

Periodic.zip Periodic.zip

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
S

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
S

C++ - Тест 003. Условия и циклы

  • Result:57points,
  • Rating points-2
g

C++ - Test 005. Structures and Classes

  • Result:100points,
  • Rating points10
Last comments
J
JonnyJoMay 25, 2023, 2:24 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 4:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 10:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 5:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
J
JonnyJoMay 20, 2023, 11:27 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, здравствуйте! Подскажите, а почему при нажатии одной клавиши переменная countForSteps увеличивается не на 1, на 4, ведь одно действие даёт увеличение этой переменной только на единицу? …
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 4:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 14, 2021, 7:03 p.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
Evgenii Legotckoi
Evgenii LegotckoiApril 24, 2023, 3:22 a.m.
Пакеты данных между сервером и клиентами Привет. Если классы имеют что-то общее в полях, а также общую идеологию и их можно вписать в иерархию наследования, то в первую очередь переписать так, чтобы один базовый класс объединял в…

Follow us in social networks