2016-07-08 34 views
-3

基本上,我想创建一个程序来检查月份,日期和年份,并且如果满足月份和日期条件,将执行代码。在某个日期执行代码?

例如,假设日期是7月8日,2016年

比方说,我有一些代码,只是想程​​序输出的“Hello world!”在这个日期。

我想要这个代码在2016年7月8日执行,没有其他日期。我将如何去做这件事?

+0

欢迎来到Stackoverflow!您能否详细说明您的问题,比如代码或其他事情,以便人们能够尽早解决问题并帮助您?谢谢! – JRSofty

回答

2

要到运行您的程序在某个时间,您必须依赖外部工具,如cron或Windows任务调度程序。程序无法运行本身,如果它不是已经:-)

运行。如果你的代码运行,并且您只是希望它推迟采取行动,直到某个特定的时间,这就是在ctime头所有的东西是。

您可以使用time()localtime()将当地时间变为struct tm,然后检查字段以检查某些特定时间是否为当前时间。如果是这样,请执行您的操作。如果没有,请循环并重试(如果需要,可以适当延迟)。

举例来说,这里有一个程序,它输出的时间,但只在五秒钟的界限:

#include <iostream> 
#include <iomanip> 
#include <ctime> 
using namespace std; 

int main() { 
    time_t now; 
    struct tm *tstr; 

    // Ensure first one is printed. 

    int lastSec = -99; 

    // Loop until time call fails, hopefully forever. 

    while ((now = time(0)) != (time_t)-1) { 
     // Get the local time into a structire. 

     tstr = localtime(&now); 

     // Print, store seconds if changed and multiple of five. 

     if ((lastSec != tstr->tm_sec) && ((tstr->tm_sec % 5) == 0)) { 
      cout << asctime(tstr); 
      lastSec = tstr->tm_sec; 
     } 
    } 

    return 0; 
} 
1

我会用std::this_thread::sleep_until(time_to_execute);其中time_to_executestd::chrono::system_clock::time_point

现在问题变成:您如何将system_clock::time_point设置为正确的值?

Here is a free, open-source library用于将system_clock::time_point设置为特定日期。使用它看起来像:

using namespace date; 
std::this_thread::sleep_until(sys_days{jul/8/2016}); 

这将触发于2016-07-08 00:00:00 UTC。如果您宁愿根据您当地的时间或某个任意时区here is a companion library来实现该功能。

您也可以下拉到C API并设置std::tm的字段值,将其转换为time_t,然后将其转换为system_clock::time_point。它更丑陋,更容易出错,并且不需要第三方库。