【问题标题】:Executing Code on a Certain Date?在特定日期执行代码?
【发布时间】:2016-11-10 15:07:18
【问题描述】:

基本上,我想创建一个程序来检查月、日和年,如果月和日条件都满足,将执行代码。

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

假设我有一些代码只是想让程序输出“Hello world!”在这个日期。

我希望此代码在 2016 年 7 月 8 日而不是其他日期执行。我该怎么办?

【问题讨论】:

  • 欢迎来到 Stackoverflow!您能否详细说明您的问题,例如代码或其他东西,以便人们可以及早解决您的问题并为您提供帮助?谢谢!

标签: c++ date time


【解决方案1】:

要在特定时间运行您的程序,您必须依赖外部工具,例如 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;
}

【讨论】:

    【解决方案2】:

    我会使用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。它更丑,更容易出错,并且不需要 3rd 方库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多