juce - 定时器(Timer)

1. Timer 类的作用

在JUCE中,Timer是一个用来处理定时任务的类,类似于其他框架中的定时器。用户可以通过继承Timer类并重写timerCallback()方法来实现定时执行某些代码的功能。然后,需要调用startTimer()来启动定时器,设置间隔时间,单位是毫秒。停止的话可以用stopTimer()。

  • 定时回调:通过继承 Timer 并重写 timerCallback() 方法,可以在设定的时间间隔内重复执行任务。

  • 线程安全:回调默认在消息线程(主 UI 线程)执行,适合更新 UI,但需避免耗时操作阻塞线程。

  • 灵活控制:可以动态启动/停止定时器,调整时间间隔。

2. 使用步骤

2.1 继承 Timer 并重写回调

#include <JuceHeader.h>

class MyTimer : public juce::Timer {
public:
    void timerCallback() override {
        // 定时执行的代码
        juce::Logger::writeToLog("Timer triggered!");
    }
};

2.2 启动和停止定时器

MyTimer timer;

// 启动定时器,间隔 1000 毫秒(1 秒)
timer.startTimer(1000);

// 停止定时器
timer.stopTimer();

2.3 检查定时器状态

if (timer.isTimerRunning()) {
    juce::Logger::writeToLog("Timer is active.");
}

3. 实际应用示例:更新 UI 组件

如果用在 JUCE 组件(如 Component)中,可以直接继承 Timer(因为 Component 本身间接继承自 Timer):

class MyComponent : public juce::Component, public juce::Timer {
public:
    MyComponent() {
        startTimer(500); // 每 500 毫秒触发一次
    }

    void timerCallback() override {
        // 更新 UI(例如修改 Label)
        label.setText("Time: " + juce::Time::getCurrentTime().toString(), juce::dontSendNotification);
    }

private:
    juce::Label label;
};

4. 注意事项

  1. 避免阻塞主线程:如果 timerCallback() 中有耗时操作(如文件读写、复杂计算),使用子线程(如 Time::callAfterDelay 或 Thread 类)。

  2. 单次定时器:在回调中调用 stopTimer() 可实现单次触发。

     
    void timerCallback() override {
        juce::Logger::writeToLog("This runs only once.");
        stopTimer();
    }
  3. 对象生命周期:确保定时器停止在对象销毁前(如在析构函数中调用 stopTimer())。

     
    ~MyComponent() {
        stopTimer();
    }
  4. 时间精度:定时器精度依赖操作系统,高精度需求可考虑 HighResolutionTimer


5. 完整代码示例

#include <JuceHeader.h>

class MainContentComponent : public juce::Component, public juce::Timer {
public:
    MainContentComponent() {
        addAndMakeVisible(label);
        label.setFont(juce::Font(16.0f));
        startTimer(1000); // 1 秒间隔
        setSize(400, 300);
    }

    void timerCallback() override {
        //label.setText(juce::Time::getCurrentTime().toString(), juce::dontSendNotification);
        label.setText(juce::Time::getCurrentTime().toString(1,1), juce::dontSendNotification);
    }

    void resized() override {
        label.setBounds(getLocalBounds().removeFromTop(50));
    }

private:
    juce::Label label;
};

// 在 MainWindow 中加载组件
class MyWindow : public juce::DocumentWindow {
public:
    MyWindow() : DocumentWindow("Timer Demo", juce::Colours::lightgrey, DocumentWindow::closeButton) {
        setContentOwned(new MainContentComponent(), true);
        centreWithSize(getWidth(), getHeight());
        setVisible(true);
    }

    void closeButtonPressed() override {
        juce::JUCEApplication::getInstance()->systemRequestedQuit();
    }
};

通过上述方法,你可以轻松在 JUCE 应用中实现定时任务。如果需要更高精度或后台任务,可进一步研究 HighResolutionTimer 或 Thread 类。

 

 

posted @ 2025-05-23 15:55  [BORUTO]  阅读(39)  评论(0)    收藏  举报