C++ C++;让功能在某个时间无中断地激活

C++ C++;让功能在某个时间无中断地激活,c++,C++,标题说明了一切。基本上,我希望能够在某个时间激活某个功能,但我希望这样做不会中断用户。在此之前,我一直使用sleep_来实现这个想法,直到: cout << "set time" << endl; cin >> time; sleep_until (system_clock::from_time_t (timegm(&time))); someFunction(); 编辑3:我也尝试过这个方法: std::thread t(&Schedule

标题说明了一切。基本上,我希望能够在某个时间激活某个功能,但我希望这样做不会中断用户。在此之前,我一直使用sleep_来实现这个想法,直到:

cout << "set time" << endl;
cin >> time;
sleep_until (system_clock::from_time_t (timegm(&time)));
someFunction();
编辑3:我也尝试过这个方法:

std::thread t(&Schedule::timeAlert, this, time1);
t.join();
但我有这个问题

error: invalid use of ‘this’ in non-member function
  std::thread t(&Schedule::timeAlert, this, time1);

尽管timeAlert在my.h文件下公开,并且在我的cpp文件中被标记为Schedule::。

只需使用一个伪函数和一个线程:

#include <thread>
#include <chrono>
#include <iostream>

using namespace std;

void invokeSomeFunctionAfter(int time) {
    //since we wait in another thread the main function will not be blocked
    this_thread::sleep_for(chrono::milliseconds(time));
    cout << "I was called after " << time  << "ms" << endl;
    someFunction();
}

int main() {
    cout << "set time" << endl;
    int time;
    cin >> time;
    //start a new thread with the given time which will wait
    thread t(invokeSomeFunctionAfter, time);
    //do more stuff

    //wait for the thread to terminate
    t.join();
    return 0;
}

您可以在单独的线程中启动该函数。您可以在主帖子中使用Windows的守护进程或任务计划程序。我希望他们能够在我的程序中做不同的事情。也就是说,如何为函数启动新线程?可能是执行异步任务的最简单方法。不过要注意,一旦开始使用多线程,您就将自己暴露在竞争条件和其他新的复杂性中,而在单线程上下文中您不必担心这些。确保了解线程同步是如何工作的。利用事件循环和计时器+回调函数。建议在
join
ing线程上添加一个快速位。对下行投票感到好奇。“无效使用void”。@Monzaku你能详细说明一下吗?对我来说,这段代码在msvc14下编译得很好。如果你能指出问题所在,那就太好了。道歉。我用两个片段编辑了这篇主要文章。
error: invalid use of ‘this’ in non-member function
  std::thread t(&Schedule::timeAlert, this, time1);
#include <thread>
#include <chrono>
#include <iostream>

using namespace std;

void invokeSomeFunctionAfter(int time) {
    //since we wait in another thread the main function will not be blocked
    this_thread::sleep_for(chrono::milliseconds(time));
    cout << "I was called after " << time  << "ms" << endl;
    someFunction();
}

int main() {
    cout << "set time" << endl;
    int time;
    cin >> time;
    //start a new thread with the given time which will wait
    thread t(invokeSomeFunctionAfter, time);
    //do more stuff

    //wait for the thread to terminate
    t.join();
    return 0;
}
Schedule mySchedule    
std::thread t(&Schedule::timeAlert, &mySchedule, time);
t.join();