Jan 16, 2018 at 3:28am UTC
Hi! I hope you can help me out here,
I've been trying to get a code that will
sends a signal of 0.5 secs, every hour
from 9am to 6pm
and then from 6pm onwards it resets back to 9am and restarts the whole process
do I use chrono?
Last edited on Jan 16, 2018 at 4:10am UTC
Jan 16, 2018 at 12:56pm UTC
Last edited on Jan 16, 2018 at 12:57pm UTC
Jan 16, 2018 at 2:46pm UTC
edit:
It sounds like for your purposes, you don't care about millisecond precision, so I suggest using lastchance's methods, sleep_for and sleep_until. But I'll still keep my answer here for reference in case you want to do something similar to it.
original post:
I'm not sure if boost::asio is more accurate than std::thread's sleep_for, but here's an example of boost::asio with boost::posix_time (see first answer).
https://stackoverflow.com/questions/12904098/c-implementing-timed-callback-function
Also in that SO thread is someone giving an example using Win32 API's SetTimer function. I copied it and modified it to work on my Windows system:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#define STRICT 1
#include <windows.h>
#include <iostream>
using namespace std;
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT_PTR idEvent, DWORD dwTime)
{
cout << "CALLBACK " << dwTime << endl;
}
int main(int argc, char *argv[], char *envp[])
{
int Counter=0;
MSG Msg;
unsigned milliseconds = 2000;
UINT TimerId = SetTimer(NULL, 0, milliseconds, &TimerProc); //2000 milliseconds
cout << "TimerId: " << TimerId << '\n' ;
if (!TimerId)
return 16;
while (GetMessage(&Msg, NULL, 0, 0))
{
++Counter;
if (Msg.message == WM_TIMER)
cout << "Counter: " << Counter << "; timer message\n" ;
else
cout << "Counter: " << Counter << "; message: " << Msg.message << '\n' ;
DispatchMessage(&Msg);
}
KillTimer(NULL, TimerId);
return 0;
}
Edit 2:
Note there's a better way to handle GetMessage,
see
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644936(v=vs.85).aspx
Last edited on Jan 16, 2018 at 2:52pm UTC