Hello DaniWeb,

So I have a function:

time_t current_time = time( NULL );
while ( 1 )
      if ( time( NULL ) == current_time + 3600 ) // execute body every hour
      {
        // stuff
        current_time = time( NULL );
      }

This is the only way I could think of doing it, but it just doesn't seem right to have to use while(1) . When I look at the processor's activity, it is hogging a lot of CPU power and making tons of system calls probably for time() , since it has to check the condition over and over and over.

Is there a less expensive way to do this? Thank you in advance

Recommended Answers

All 4 Replies

If you only want it to do something every hour, then put it to sleep for an hour - this is MS-Windows, *nix would be sleep() with lower-case 's'.

while ( 1 )
{
    Sleep(60*60*1000); // sleep for one hour
    // stuff
}

seems like Microsoft always has to do things slightly differently... thanks again Ancient Dragon, that was exactly what I was looking for, reduced CPU usage significantly

You could also setup a timer, that will call a callback and/or send a windows message.

You could also setup a timer, that will call a callback and/or send a windows message.

Hi,
Could you please exaplain a bit about how to solve this using a timer?

many thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.