2016-07-08 63 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。它更醜陋,更容易出錯,並且不需要第三方庫。