如何使用C++ 11创建计时器事件?
我需要这样的东西:“从现在起1秒后给我打电话”。
有图书馆吗?
发布于 2013-02-03 02:46:57
做了一个简单的实现,我相信这是你想要实现的。您可以将类later与以下参数一起使用:
的参数完全相同
您可以将std::chrono::milliseconds更改为std::chrono::nanoseconds或microseconds以获得更高的精度,并添加第二个int和for循环来指定运行代码的次数。
给你,好好享受吧:
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later
{
public:
template <class callable, class... arguments>
later(int after, bool async, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
if (async)
{
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}).detach();
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}
}
};
void test1(void)
{
return;
}
void test2(int a)
{
printf("%i\n", a);
return;
}
int main()
{
later later_test1(1000, false, &test1);
later later_test2(1000, false, &test2, 101);
return 0;
}两秒钟后的输出:
101发布于 2017-10-05 01:59:32
Edward的异步解决方案:
很简单,而且可能对你有用。
我还想给出一个更高级的版本,它具有以下优点:
这在大型软件项目中可能特别有用,在这些项目中,您的流程中有许多重复执行的任务,并且您关心资源使用(线程)和启动开销。
想法:有一个服务线程来处理所有注册的定时任务。为此,请使用boost io_service。
代码类似于:http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html
#include <cstdio>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
t2.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
// both prints happen at the same time,
// but only a single thread is used to handle both timed tasks
// - namely the main thread calling io.run();
io.run();
return 0;
}发布于 2018-10-29 12:52:03
使用RxCpp,
std::cout << "Waiting..." << std::endl;
auto values = rxcpp::observable<>::timer<>(std::chrono::seconds(1));
values.subscribe([](int v) {std::cout << "Called after 1s." << std::endl;});https://stackoverflow.com/questions/14650885
复制相似问题