Evgenii Legotckoi
Dec. 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.

  1. cmake_minimum_required (VERSION 3.8)
  2.  
  3. project(Periodic)
  4.  
  5. set(CMAKE_CXX_STANDARD 17)
  6. set(Boost_USE_STATIC_LIBS ON)
  7.  
  8. find_package(Boost 1.68 REQUIRED COMPONENTS thread)
  9.  
  10. set(SOURCE_FILES
  11. Periodic/main.cpp
  12. Periodic/PeriodicTask.cpp)
  13.  
  14. SET(HEADER_FILES
  15. Periodic/PeriodicTask.h)
  16.  
  17. if(Boost_FOUND)
  18. include_directories(${Boost_INCLUDE_DIRS})
  19. add_executable(Periodic ${SOURCE_FILES} ${HEADER_FILES})
  20. target_link_libraries(Periodic ${Boost_LIBRARIES})
  21. 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
  1. #pragma once
  2.  
  3. #include <boost/thread.hpp>
  4. #include <boost/chrono.hpp>
  5. #include <functional>
  6. #include <atomic>
  7.  
  8. class PeriodicTask
  9. {
  10. public:
  11. explicit PeriodicTask(const boost::chrono::milliseconds &period, const std::function<void()> &func);
  12.  
  13. virtual ~PeriodicTask();
  14.  
  15. private:
  16. boost::chrono::milliseconds m_period; // Task period
  17. std::function<void()> m_func; // The function that will perform the periodic task
  18. 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
  19. boost::thread m_thread; // Task thread
  20. };

PeriodicTask.cpp

  1. #include "PeriodicTask.h"
  2.  
  3. PeriodicTask::PeriodicTask(const boost::chrono::milliseconds &period, const std::function<void()> &func) :
  4. m_period(period),
  5. m_func(func),
  6. m_running(true)
  7. {
  8. // Create a stream object to perform a periodic task.
  9. m_thread = boost::thread([this]
  10. {
  11. while (m_running)
  12. {
  13. // To perform a task with a specific period, immerse the stream in a dream after each task execution.
  14. boost::this_thread::sleep_for(m_period);
  15. if (m_running)
  16. {
  17. // perform the task
  18. m_func();
  19. }
  20. }
  21. });
  22. }
  23.  
  24. PeriodicTask::~PeriodicTask()
  25. {
  26. // When destroying an object with a periodic task
  27. m_running = false;
  28. // interrupt the flow, otherwise the program will not release system resources until the flow comes out of sleep
  29. // this is critical if the trigger period of the task is measured in tens of seconds and more
  30. m_thread.interrupt();
  31. m_thread.join();
  32. }

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.

  1. #include "PeriodicTask.h" // We connect the class header file to perform periodic tasks.
  2.  
  3. #include <iostream>
  4.  
  5. int main(int argc, const char* argv[])
  6. {
  7. std::cout << "Start program" << std::endl;
  8. int count = 0;
  9. // Create a periodic task with a period of 1 second
  10. PeriodicTask p(boost::chrono::seconds{ 1 }, [&count]() {
  11. // Display the counter and increment it by one.
  12. std::cout << count++ << std::endl;
  13. });
  14.  
  15. // Stop the main program flow for 10 seconds so that the periodic task can work 10 times.
  16. boost::this_thread::sleep_for(boost::chrono::seconds{ 10 });
  17. std::cout << "End program" << std::endl;
  18. return 0;
  19. }

Coclusion

As a conclusion I attach the archive with the project.

Periodic.zip Periodic.zip

Recommended articles on this topic

By article asked0question(s)

1

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html