如何睡到下周日

Fro*_*art 12 c++ boost

我怎么能在下周日睡觉前使用加强?我可以将boost::gregorian::date对象转换为boost::this_thread::sleep_until可以处理的东西吗?可能吗?

#include <boost/date_time.hpp>

int main()
{
    boost::gregorian::date current_date(boost::gregorian::day_clock::local_day());
    boost::gregorian::greg_weekday next_sunday_date(boost::gregorian::Sunday);
    boost::gregorian::date next_weekday_date = next_weekday(current_date, next_sunday_date);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 8

这就是我想出来的.

请注意,我使代码通常更具可读性.这一点很重要,不仅仅是为了将来的维护,还因为它可以让你"看到森林中的树木" - 这反过来又让你能够记住心理上的重要概念.

至少,这对我有帮助.

编辑 DyP提供了一种使用方式sleep_until(在极少数情况下会表现得更准确,例如在睡眠期间时钟会发生变化).

#include <boost/date_time.hpp>
#include <boost/date_time/time_clock.hpp>
#include <iostream>

#include <thread>
#include <chrono>

int main()
{
    using namespace boost::gregorian;
    using boost::posix_time::ptime;
    using clock = boost::posix_time::microsec_clock; // or: boost::posix_time::second_clock;

    auto today       = date(day_clock::local_day());
    auto at_sunday   = greg_weekday(Sunday);
    auto next_sunday = next_weekday(today, at_sunday);

#if 1
    auto as_tm         = to_tm(next_sunday);
    auto as_time_t     = mktime(&as_tm);
    auto as_time_point = std::chrono::system_clock::from_time_t(as_time_t);

    std::this_thread::sleep_until(as_time_point);
#else
    auto duration = (ptime(next_sunday) - clock::local_time());
    auto msecs    = duration.total_milliseconds();
    std::cout << msecs << "\n";

    std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
#endif
}
Run Code Online (Sandbox Code Playgroud)

看到它在Coliru上编译(明显超时)


dut*_*utt 2

这听起来不稳定。如果用户关闭计算机或进入休眠状态,或者只是重新启动怎么办?

我会通过以下两种方式之一来做到这一点:

  1. 添加计划任务(或任何 Windows/OSX 术语)/cronjob (linux) 并将其设置为在周日运行。

  2. 将其添加到自动启动并定期(每 10/30/60 分钟一次)检查是否是星期日。

这两种方式都比休眠 5 天更好地处理重启/关闭/休眠。