gpt4 book ai didi

c++ 每 10 分钟运行一次

转载 作者:行者123 更新时间:2023-11-28 04:36:47 27 4
gpt4 key购买 nike

我希望这个程序每启动(调用)10 分钟运行一次。

但我没有找到解决方案,即如何在 C++ 代码 (man.exe) 上每 10 分钟调用一次(启动)程序。我想在 visual studio 2013 中使用代码

 int runevery() {
system("start man.exe");
return true;
}

调用:

#ifdef MAN_RUN
runevery();
#endif

提前感谢您的帮助!

最佳答案

您可以创建另一个线程来定期执行该函数直到停止。示例:

#include <mutex>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>
#include <condition_variable>

class PeriodicAction {
std::mutex m_;
std::condition_variable c_;
bool stop_ = false;
std::function<void()> const f_;
std::chrono::seconds const initial_delay_;
std::chrono::seconds const delay_;
std::thread thread_;

bool wait(std::chrono::seconds delay) {
std::unique_lock<std::mutex> lock(m_);
c_.wait_for(lock, delay, [this]() { return stop_; });
return !stop_;
}

void thread_fn() {
for(auto delay = initial_delay_; this->wait(delay); delay = delay_)
f_();
}

public:
PeriodicAction(std::chrono::seconds initial_delay,
std::chrono::seconds delay,
std::function<void()> f)
: f_(move(f))
, initial_delay_(initial_delay)
, delay_(delay)
, thread_(&PeriodicAction::thread_fn, this)
{}

~PeriodicAction() {
this->stop();
thread_.join();
}

void stop() {
{
std::unique_lock<std::mutex> lock(m_);
stop_ = true;
}
c_.notify_one();
}
};

char const* now_c_str() {
auto time_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return std::ctime(&time_t);
}

int main(int ac, char**) {
using namespace std::literals::chrono_literals;

// Print current time for the next 5 seconds and then terminate.
PeriodicAction a(0s, 1s, []() { std::cout << now_c_str(); });
std::this_thread::sleep_for(5s);
}

应用于您的案例:

PeriodicAction a(0s, 600s, [](){ system("start man.exe"); });

关于c++ 每 10 分钟运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51190376/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com