12

使用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);
    // ...
}
4

2 回答 2

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
}

看到它在 Coliru 上编译显然超时

于 2013-10-11T08:33:55.507 回答
2

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

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

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

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

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

于 2013-10-11T07:35:29.460 回答