You are here:

C++/running a thread at a specific time in C++


Hi there,
I just have one simple little C/C++ question for
you. I'm writing some code that has multiple
threads running in various infinite loops. I
would like one of the threads to wake up at a
specific time, say 11:00am, and run then go back
to sleep and wake up the next day at 11:00am and
run then go back to sleep and so on and so on.
Any idea as to how to do that? I am aware of the
sleep() function but I don't want the process to
just wake up every 24 hours I want it to wake up
at a specific time. I am running on a SuSe Linux

Thanks so much for your help in advance,

Hello Joe, thank you for the question.

Well, in Windows I know to retrieve system time you call GetSystemTime() and pass it a pointer to a SYSTEMTIME structure. I've only had limited experience with Linux, but I believe you can include Windows.h and use that function and it should compile fine in Linux. If not, I have a couple functions here from a past Linux project that someone else wrote that I'll let you have, they look like they would be pretty helpful for what you are trying to do:

static struct timeval startTime;
static struct timeval currentTime;

void TimerReset(void)
  gettimeofday(&startTime, 0);

double TimerGetElapsedTime(void)
  double t1, t2;
  gettimeofday(¤tTime, 0);
  t1 = (double)startTime.tv_sec + (double)startTime.tv_usec*0.000001;
  t2 = (double)currentTime.tv_sec + (double)currentTime.tv_usec*0.000001;
  return t2 - t1;

This code was contained in its on Timer.c file. If you can, maybe you could look at the gettimeofday function and see if it helps at all. These couple of options should help you out.

I hope this information was helpful.

- Eddie

Follow Up

Also, just in case you didn't know you have to
#include <sys/time.h> as well.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 All rights reserved.