使用C++在特定时间打开链接



所以我正在尝试编写一个C++控制台程序,该程序在特定时间打开与Web浏览器的链接。时钟更新正常,外壳线打开链接,但我无法让这两者一起工作。这是我的代码:

#include <Windows.h>
#include <shellapi.h>
#include <ctime>
#include <chrono>
#include <thread>
using namespace std;
int main(int argc, char* argv[])
{
string url = "https://www.google.com";
while (true) {
system("cls");
time_t now = time(0);
char* dt = ctime(&now);
cout << dt;
while (dt == "Mon May 18 09:48:00 2020") {
ShellExecute(NULL, "open", url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}

至少对我来说,你的代码似乎有点混乱。目前还不清楚为什么我们会一次睡一秒钟,直到我们到达目标。更糟糕的是,如果其中一个睡眠呼叫碰巧太长,我们可能会超过标记,并且永远不会执行所需的操作。更糟糕的是,如果我们确实达到了所需的时间,内部循环看起来像是一个无限循环,因为只要字符串有所需的时间,它就会继续重新执行——但我们没有将字符串更新到循环中的当前时间,所以如果我们确实达到了那个时间,字符串将永远保持不变。

至少根据您的描述,我们只想选择一个时间,睡到那时,然后执行命令。为此,似乎这个一般订单上的代码就足够了:

#include <windows.h>
#include <chrono>
#include <thread>
#include <iostream>
int main() {
// For the moment, I'm just going to pick a time 10 seconds into the future:
time_t now = time(nullptr);    
now += 10;
// compute that as a time_point, then sleep until then:
auto then = std::chrono::system_clock::from_time_t(now);
std::this_thread::sleep_until(then);
// and carry out the command:
ShellExecute(NULL, "open", "https://www.google.com",
NULL, NULL, SW_SHOWNORMAL);
}

在您的情况下,您显然想要指定数据和时间。这稍微难以测试,但从根本上没有太大的不同。您可以将所需的日期/时间填充到struct tm中,然后使用mktime将其转换为time_t。一旦你有一个time_t,你使用std::chrono::system_clock::from_time_t,如上面的代码,然后从那里继续。如果需要从字符串开始,可以使用std::get_time将字符串数据转换为struct tm。因此,对于您指定的日期/时间,我们可以执行以下操作:

#include <windows.h>
#include <chrono>
#include <thread>
#include <iostream>
#include <sstream>
#include <iomanip>
auto convert(std::string const &s) {
std::istringstream buffer(s);
struct tm target_tm;
buffer >> std::get_time(&target_tm, "%a %b %d %H:%M:%S %Y");
time_t target = mktime(&target_tm);
return std::chrono::system_clock::from_time_t(target);
}
int main() {
auto target = convert("Mon May 18 09:48:00 2020");
std::this_thread::sleep_until(target);
ShellExecute(NULL, "open", "https://www.google.com",
NULL, NULL, SW_SHOWNORMAL);
}

最新更新