2011-11-18 98 views
0

好的,所以我的问题是,我该如何制作一个基本上执行程序其余部分的程序,例如12pm。例如一些非现实的代码:程序在特定时间执行

#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; 
} 

有谁知道我该怎么做类似的事情?

+3

您是否试图重塑['cron'](http://en.wikipedia.org/wiki/Cron)? –

+0

不,只需要我的程序在特定时间执行其余的代码。对于windows。 – shix

+4

或[Windows计划程序](http://support.microsoft.com/kb/308569),因为这具体被标记为'winapi'。 “Scheduler API”记录在[这里](http://msdn.microsoft.com/en-us/library/windows/desktop/aa383608(v = vs.85).aspx) –

回答

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

这很好用。 :D非常感谢。 – shix

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 
}