程序在某个时间执行

时间:2011-11-18 23:26:07

标签: c winapi time

好吧我的问题是,如何制作一个基本上执行程序其余部分的程序,例如下午12点。例如一些非现实的代码:

#include <stdio.h>
#include <time.h>

int main()
{

     Get_time() //Gets system time

     if(time() == 254pm ){ //if time is 2:54pm

             printf("Time: 2:54pm\n");
         }

      else printf("Program can not execute at this time.\n");

      return 0;
 }

有谁知道我可以做些类似的事情吗?

2 个答案:

答案 0 :(得分:2)

使用localtime获取当前时间。

#include <stdio.h>
#include <time.h>

int main ()
{
    // Get system time
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    // Check
    if(timeinfo->tm_hour == 14 && timeinfo->tm_min == 54)
    {
        printf("Time: 2:54pm\n");
    }

  return 0;
}

答案 1 :(得分:0)

有很多方法可以做到这一点,但重要的是保持CPU免费。否则无限循环,你会花费大量资源。我建议使用Sleep()或像boost库这样的智能等待机制。 Sleep()对您来说简单得多,您只需要包含windows.h

示例代码:

#include <windows.h>
#include <time.h> 

int main() {
    int timeDelta = ...; // calculate time delta in miliseconds here (12 PM today - now)
    Sleep(timeDelta);
    // execute your code here
}