温馨提示×

如何在C++线程类中实现定时任务

c++
小樊
82
2024-08-29 22:51:42
栏目: 编程语言

在 C++ 中,可以使用 和<chrono> 库来实现线程类中的定时任务

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

class TimerThread {
public:
    TimerThread(int interval) : interval_(interval), stop_signal_(false) {}

    void start() {
        thread_ = std::thread(&TimerThread::execute, this);
    }

    void stop() {
        std::unique_lock<std::mutex> lock(mutex_);
        stop_signal_ = true;
        cv_.notify_one();
        lock.unlock();
        if (thread_.joinable()) {
            thread_.join();
        }
    }

private:
    int interval_;
    bool stop_signal_;
    std::thread thread_;
    std::mutex mutex_;
    std::condition_variable cv_;

    void execute() {
        while (true) {
            std::unique_lock<std::mutex> lock(mutex_);
            cv_.wait_for(lock, std::chrono::seconds(interval_), [this] { return stop_signal_; });
            if (stop_signal_) {
                break;
            }
            lock.unlock();
            task(); // 执行定时任务
        }
    }

    void task() {
        // 在这里编写需要定时执行的任务
        std::cout << "Task executed!"<< std::endl;
    }
};

int main() {
    TimerThread timer(5); // 设置定时任务间隔为 5 秒
    timer.start();

    std::this_thread::sleep_for(std::chrono::seconds(20)); // 让主线程休眠 20 秒

    timer.stop();

    return 0;
}

在这个示例中,我们创建了一个名为 TimerThread 的类,它接受一个表示定时任务间隔的参数。start() 方法用于启动线程,而 stop() 方法用于停止线程。execute() 方法是线程的主体,它使用条件变量等待指定的时间间隔,然后执行定时任务。

请注意,这个示例仅用于演示目的。在实际项目中,您可能需要根据需求对其进行修改和优化。

0