I have to display 3 images in my application window, there should be 10 seconds of delay while displaying each image(i.e. each image should stay for 10 seconds).
How can i do this using ontimer() without using sleep().
Use ON_WM_TIMER()
SetTimer( TIMER_ID, 10000, NULL);
Here TIMER_ID you can pass any unique id.
10000 milliseconds = 10 seconds
void CYOURDlg::OnTimer(UINT_PTR nIDEvent)
{
if(nIDEvent == TIMER_ID) // check timer Id
{
// Write your code to show exe
}
CDialog::OnTimer(nIDEvent);
}
This will call every 10 seconds as delay we have given 10 seconds.
you can call KillTimer(TIMER_ID) when you don't want to run timer.
Related
There is a task to set a timer that will work in a couple of months. I ran into a problem with QTimer::start(int msec) time is specified in int and also in milliseconds. It turns out I can specify 2147483647 milliseconds, which is a little less than a month. I used to use crontab, but I had to abandon it.
Code example:
uint sec_prediction, sec_now, answer;
QDateTime now = QDateTime::currentDateTime();
sec_now = now.toTime_t();
QLocale mylocale(QLocale::English);
qDebug() << mylocale.toString(now, "MMM d hh:mm:ss") << sec_now;
QDateTime payment = QDateTime::currentDateTime();
payment = payment.addMonths(3);
sec_prediction = payment.toTime_t();
qDebug() << mylocale.toString(payment, "MMM d hh:mm:ss") << sec_prediction;
answer = sec_prediction - sec_now;
qDebug() << answer << " - After this time, the timer should start. \n";
QTimer timer;
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(processQueue()));
timer.start(answer * 1000);
Console output:
"Jan 7 00:42:38" 1673041358
"Apr 7 00:42:38" 1680817358
7776000 - After this time, the timer should start.
QObject::startTimer: Timers cannot have negative intervals
I am using Qt 4.8
Grateful for help
Since you are using c++98 you can use libuv (C library) which supports timers
uv_timer_t timer_req; // Timers invoke the registered callback after a certain
// time has elapsed since the timer was started.
uv_timer_init(loop, &timer_req); // Docs show how to create an event loop
// This call is non blocking but YOU have to make
// sure your program still runs after a month.
uv_timer_start(&timer_req, callback, 5000, 2000);
// here put a month's worth of secs ^^ ^^
// optionally set this to repeat ^^
// After waiting for "interval sesc" your callback runs
I see that Qt4.8 doesn't have the convenient QTimer::CallOnTimeout method, but it provides a QTimer class which is wired a bit differently:
// Create a QTimer, connect its timeout() signal to the
// appropriate slots, and call start(). From then on it
// will emit the timeout() signal at constant intervals.
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000); // 1000 milliseconds timer.
Shameless plug of my C++ chrono-scheduler library. Using it would look like this:
#include "scheduler.h"
{
bool compensate = true; // a README explains
unsigned nWorkers = 1; // these values in the repo.
// 1. Create a scheduler.
ttt::CallScheduler plan(compensate, nWorkers);
// 2. Add your task.
auto myTask = []{
// You may want to repeat in another month
return ttt::Result::Finish;
};
auto token = plan.add(
myTask, // User tasks are std::function<ttt::Result()>
24h * 30, // Interval for execution or repetition
false); // Whether to immediately queue the task for execution
// 3. Wait a month ....
}
Essentially the scheduler has a pool of threads that:
Register tasks
Execute tasks at the specified intervals
Potentially re-register the tasks if they need re-running
This is the most general solution to the problem of adding ad-hoc as many tasks as you want, with millisecond (and even less) granularity without blocking the caller or the execution context. But the logic found within can be extracted and simplified for your case.
I get an average frame rate from the EVR renderer using the IQualProp::get_AvgFrameRate method. It worked well but after call of Pause/Run in the DirectShow graph I got wrong values of frame rate. Here some my solutions:
Standard solution:
bool Pause()
{
IMediaControl* pMediaControl;
pMediaControl->Pause();
}
bool Run()
{
IMediaControl* pMediaControl;
pMediaControl->Run();
}
After pMediaControl->Run() the renderer shows me the frame rate values in two times less than it is necessary. But during 10-15 sec those values are restored.
Via Stop() method:
bool Pause()
{
IMediaControl* pMediaControl;
pMediaControl->Stop();
pMediaControl->Pause();
}
bool Run()
{
IMediaControl* pMediaControl;
pMediaControl->Run();
}
Into the Pause() I add pMediaControl->Stop(). After Run() I get the right frame rate but the renderer freezes for 10-15 sec.
Using IMediaFilter::Run()
bool Pause()
{
IMediaControl* pMediaControl;
pMediaControl->Stop();
pMediaControl->Pause();
}
bool Run()
{
IMediaFilter* pMediaFilter;
pMediaFilter->Run(1000000); //delay 10ms
}
Here I got the nice result without freezing and wrong values. But CPU utilization is more in two times than before Pause().
Ideas?
I can return to my old schema, when I got an average frame rate by calculation of frames, but I would like to use the IQualProp::get_AvgFrameRate method.
I returned to the old schema. Rewrite the code of getting average FPS is better than the rework of three source filters
i have a question on how to program a certain sequence for my robot.
lets say if i would to program to make it run from position a to b, i have a sensor attach to it that should it detect x, it would perform an action called y at the position where it detect x, where action y doesnt change its position.
i would like the robot to continue from where it left after performing action y to go towards b. however i do not know how to pause the sequence from a to b and continue from where it left off after performing action y. i am controlling only the motor of the wheels and its timing so i can only set the speed of the wheels for a certain time.
is there a pause function in general( not sleep) in c++ and to continue running its lines of code from where it paused?
for now i do know how to reset its action but thats not what i want.
example( making the robot move from a to b in 10 seconds, detect object x at 3 seconds, do action y at position when t =3 seconds, continue motion for remaining 7 seconds after action y has been done)
You can try to use some event (message) driving architecture like the following pseudo code:
vector<action> action_sequence={do_a,do_b,do_c};
int i=0;
while(1)
{
e = WaitForMessage();
switch(e.code)
{
case do_action:
action_sequence[i].run();//perform an action
...//some code to have a scheduler thread to send next
//do_action message in certain seconds to this thread.
i++;
default:
...
}
}
The answer would depend on your code, are you using windows messaging, are you using thread, etc. Assuming that you are using neither, just linear code you could implement your own sleep function which is passed a function by the caller which is used to access if the sleep should be preempted. If preempted, then the function returns the time left so the action can be continued later.
This allows linear code to handle your situation. I knocked up a sample. Will explain the bits.
typedef bool (*preempt)(void);
DWORD timedPreemptableAction (DWORD msTime, preempt fn)
{
DWORD startTick = GetTickCount();
DWORD endTick = startTick + msTime;
DWORD currentTick;
do
{
currentTick = GetTickCount();
}
while (fn () == false && currentTick < endTick);
return currentTick > endTick ? 0 : endTick-currentTick;
}
The key function above, obtains start time in milliseconds, and will not exit until the timeout expires - or the user provided function returns true.
This user provided function could poll input devices such as a keyboard press etc. For now to match your question, I have added a user function which returns true, after 3 seconds:
DWORD startToTurnTicks = 0;
bool startToTurn (void)
{
bool preempt = false;
// TODO Implement method of preemption. For now
// just use a static timer, yep a little hacky
//
// 0 = uninitialized
// 1 = complete, no more interruptions
// >1 = starting tick count
if (startToTurnTicks == 0)
{
startToTurnTicks = GetTickCount();
}
else
{
if (startToTurnTicks != 1)
{
if ((startToTurnTicks + 3000) < GetTickCount())
{
startToTurnTicks = 1;
preempt = true;
}
}
}
return preempt;
}
Now we have a function which waits for N time and can exit, and a user function which will return true after 3 seconds, now the main call:
bool neverPreempt (void)
{
return false;
}
int main (void)
{
int appResult = 0;
DWORD moveForwardTime = 1000*10;
DWORD turnTime = 1000*3;
DWORD startTicks = GetTickCount();
printf ("forward : %d seconds in\n",
(GetTickCount()-startTicks)/1000);
moveForwardTime = timedPreemptableAction (moveForwardTime, &startToTurn);
printf ("turn : %d seconds in\n",
(GetTickCount()-startTicks)/1000);
turnTime = timedPreemptableAction (turnTime, &neverPreempt);
printf ("turn complete : %d seconds in\n",
(GetTickCount()-startTicks)/1000);
if (moveForwardTime > 0)
{
printf ("forward again : %d seconds in\n",
(GetTickCount()-startTicks)/1000);
moveForwardTime = timedPreemptableAction (moveForwardTime, &neverPreempt);
printf ("forward complete : %d seconds in\n",
(GetTickCount()-startTicks)/1000);
}
return appResult;
}
In the main code you see timedPreemptableAction is called 3 times. The first time we pass the user function which turns true after 3 seconds. This first call exits after three seconds returning 7 seconds left. The output from the app returns:
f:\projects\cmake_test\build\Debug>main
forward : 0 seconds in
turn : 3 seconds in
turn complete : 6 seconds in
forward again : 6 seconds in
forward complete : 13 seconds in
Started to move forward #0 seconds, "paused" #3 seconds, restored #6 and finished #13.
0->3 + 6->13 = 10 seconds.
I am currently using the AWS IoT SDK for the Arduino Yun, and I am running the example sketches (specifically the Thermostat simulator).
I modified the loop slightly (just changed the delay at the end) such that it looks like this:
void loop() {
if(success_connect) {
// If the desired temperature is set to a higher value, start heating.
if(desiredTemp - reportedTemp > 0.001) {reportedTemp += 0.1;}
// If the desired temperature is set to a lower value, start cooling.
else if(reportedTemp - desiredTemp > 0.001) {reportedTemp -= 0.1;}
dtostrf(reportedTemp, 4, 1, float_buf);
float_buf[4] = '\0';
sprintf_P(JSON_buf, PSTR("{\"state\":{\"reported\":{\"Temp\":%s}}}"), float_buf);
print_log("shadow update", myClient.shadow_update(AWS_IOT_MY_THING_NAME, JSON_buf, strlen(JSON_buf), NULL, 5));
if(myClient.yield()) {
Serial.println("Yield failed.");
}
delay(10000); // CHANGED TO 10 SECONDS INSTEAD OF 1
}
}
For some reason, when the loop is delayed for less than 10 seconds, the shadow update has no problem repeating. But as soon as the delay is 10 seconds or more, I get this error:
Exception in thread Thread-4 (most likely raised during interpr
[ERR] command: shadow update code: -1
I changed the CMD_TIME_OUT to a higher value in the aws_iot_config_SDK.h file, but it still seems to have no effect. The reason why I'd like the timeout delay to be larger than 10 seconds is because I want to ideally have a trigger mechanism in the arduino that would update the shadow.
Question : How do you make a timer tick in the background? That is the thread that create the timer thread can still do something else while clock is ticking.
Attempt:
-Using _beginthreadex() --> It seems to have race condition
class Timer{
...
static unsigned __stdcall tick(void *param){
while(1){
Timer::timer++;
Sleep(Timer::timer*1000);
}
return 1;
}
}
.....
HANDLE time_thread = (HANDLE) _beginthreadex(0, 0, &Timer::tick,0,0,NULL);
...
//test for 20 seconds
//want to do something while the clock is not 20 seconds
//the mainthread here still has to receive input
//What is the proper way to do it?
while (Timer::getTime() != 20){
cout << Timer::getTime()
}
CloseHandle(time_thread);
...
NOTE: Iam using Visual Studio 2008, not 11 so I do not have C++11 support.
I'm not sure what's wrong with what you have here. You've created a thread that updates a member variable timer forever and your main use of it is a tight/fast loop that prints (presumably) that time until it reaches 20. What is it not doing? Technically there's a race condition of incrementing that value versus checking it in another thread, but for the purposes of this example it should be fine...
EDIT: try this for non-blocking input with full input control:
HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );
while ( true ) {
if ( WAIT_OBJECT_0 == WaitForSingleObject( hStdIn, 1000 ) ) {
// read input
INPUT_RECORD inputRecord;
DWORD events;
if ( ReadConsoleInput( hStdIn, &inputRecord, 1, &events ) ) {
if ( inputRecord.EventType == KEY_EVENT ) {
printf( "got char %c %s\n",
inputRecord.Event.KeyEvent.uChar.AsciiChar,
inputRecord.Event.KeyEvent.bKeyDown ? "down" : "up" );
}
}
}
printf( "update clock\n" );
}
I'm afraid you've misunderstood how the system timers work and how to use them - the whole point is that they automatically run in the background, so you don't have to do your own thread management.
This has examples and explanations of Windows timers in general, and you can use it if you're trying to roll your own Timer class: Timers Tutorial
This is the Timer class that comes with Windows.NET, with a code example at the bottom: Timer Class
Edited to add:
Here's a version of the Win32 timer example (from the turorial page) adapted for a non-MFC app:
int nTimerID;
void Begin(HWND hWindow_who_gets_the_tick)
{
// create the timer to alert your window:
nTimerID = SetTimer(hWindow_who_gets_the_tick, uElapse, NULL);
}
void Stop()
{
// destroy the timer
KillTimer(nTimerID);
}
See MSDN: Timer functions for details.
Then inside your window procedure, you get the WM_TIMER message and respond as you like.
Alternatively, the timer can call a user-defined procedure. See SetTimer function for details.