Cron chrono library on Raspberry Pi
On a Raspberry Pi 2, I need to call the php file regularly, typically every 100ms. I found this C ++ code that looks like it does what I need, and the test version compiles and works fine using CodeBlock on Windows. I updated wheezy RPi with the c ++ libraries from jessie using this tutorial , compiled it on Pi using g ++ - 4.9 -std = c + +14 but I don't get the output. I am very new to Linux and C ++, so any help would be appreciated. The code looks like this
#include <iostream>
#include <cstdlib>
#include <chrono>
using namespace std;
int main () {
using frame_period = std::chrono::duration<long long, std::ratio<50, 100>>;
auto prev = std::chrono::high_resolution_clock::now();
auto current = prev;
auto difference = current-prev;
while(true)
{
while (difference < frame_period{1})
{
current = std::chrono::high_resolution_clock::now();
difference = current-prev;
}
//cout << std::system("php run.php");
std::cout << "OK ";
using hr_duration = std::chrono::high_resolution_clock::duration;
prev = std::chrono::time_point_cast<hr_duration>(prev + frame_period{1});
difference = current-prev;
}
return 0;
}
Perhaps my problem is with one of the libraries or something else in the code? I'm not even sure if this is the best way to achieve what I need, as the code looks like it connects the processor in a loop at startup.
source to share
The problem is that the output is buffered by the stdio library, you need to flush the output stream so that it appears immediately:
std::cout << "OK " << std::flush;
Your solution is very inefficient because it runs through a busy cycle by constantly revising the system time between intervals.
I would use one call to get the time and then this_thread::sleep_until()
to make a program block until you want to run the script again:
#include <iostream>
#include <cstdio>
#include <chrono>
# include <thread>
int main()
{
std::chrono::milliseconds period(100);
auto next = std::chrono::high_resolution_clock::now() + period;
while (true)
{
std::this_thread::sleep_until(next);
next += period;
// std::system("php run.php");
std::cout << "OK " << std::flush;
}
}
Since you are using C ++ 14, you can also use operator""ms
literal to simplify the declaration period
:
using namespace std::literals::chrono_literals;
auto period = 100ms;
Or, more similar to the answer you found, instead of using a variable that represents 100ms, you can define a type that represents that duration, and then add units of that type (instead of 100 units of a type milliseconds
) to the next
value:
// a type that represents a duration of 1/10th of a second
using period = std::chrono::duration<long, std::ratio<1, 10>>;
auto next = std::chrono::high_resolution_clock::now() + period(1);
while (true)
{
std::this_thread::sleep_until(next);
next += period(1);
...
}
source to share