Search code examples
c++mysqldatabaseunix-timestamp

getting value of sensor each second c++


I am recently trying to store data measured by my humidity sensor into my MYSQL database. I have already programmed the necessary C++ pogramm getting the data from the sensor, storing it in my MYSQL database and getting the current UnixTime as well.

However, I´d like to store the data each second and think using a thread does not seem a neat solution for this problem. I also do not want MYSQL to insert the UnixTime automatically. I´d like to keep on using my C++ programm for that.

Does anybody know an easier approach to store the data each second with the necesarry UnixTime using C++?


Solution

  • Threads are actually a neat solution for background tasks. Consider this example:

    #include <iostream>
    #include <thread>
    #include <chrono>
    
    void everySecondTask() {
      while (true) {
        // Do actual work here, e.g. get sensor data and write to db
        std::cout << "second passed" << std::endl;
    
        std::this_thread::sleep_for(std::chrono::seconds(1));
      }
    }
    
    int main() {
      // operations and sleep in everySecondTask is done in different thread, code
      // in main is not paused.
      std::thread background(everySecondTask);
    
      // do you 200 lines of code here, while task is called every second
    
      background.join();
    }