Application kit: periodic tasks and message queuing

Application kit: periodic tasks and message queuing

  • mdo  DigitalBox
  •   KitLab
  •   February 23, 2026

In the previous KitLab articles, we explored inter-application messaging with BMessenger.

Now let's dive into periodic tasks and message queuing in Haiku.

Using BMessageRunner, you can schedule messages to be sent at regular intervals—perfect for timers, animations, and periodic updates. Combined with BMessageQueue, you gain fine control over message flow and priorities.

What is BMessageRunner?

BMessageRunner is a class that sends messages repeatedly at specified intervals. Think of it as a programmable alarm clock for your application.

Key features:

  • Periodic messaging - send messages at fixed time intervals
  • Automatic cleanup - stops when deleted or when count limit is reached
  • Flexible targeting - can send to any BHandler or BMessenger
  • Adjustable timing - change interval on the fly

The common usage is for animation timers, progress updates, auto-save functionality, polling external resources, real-time clocks and countdowns, and much more.

What is BMessageQueue?

BMessageQueue is the internal queue that stores messages before they're dispatched to handlers. While you rarely manipulate it directly, understanding it helps you grasp how Haiku's messaging works.

Every BLooper (including BApplication and BWindow) has a message queue that:

  • Stores incoming messages in arrival order
  • Allows message filtering before dispatch
  • Enables priority handling for urgent messages
  • Supports queue inspection for debugging

The Demo: Animated Counter

We'll create an application with:

  1. A counter that increments every second
  2. A BMessageRunner that triggers updates
  3. Start/Stop buttons to control the timer
  4. Display showing the count and queue statistics

This demonstrates real-time periodic messaging in action.

Source Code: TimerCounter.cpp

#include <Application.h>
#include <Window.h>
#include <View.h>
#include <Button.h>
#include <StringView.h>
#include <MessageRunner.h>
#include <MessageQueue.h>
#include <String.h>
#include <stdio.h>

const uint32 MSG_TIMER_TICK = 'TICK';
const uint32 MSG_START_TIMER = 'STRT';
const uint32 MSG_STOP_TIMER = 'STOP';
const uint32 MSG_RESET_COUNTER = 'RSET';

class TimerView : public BView {
public:
    TimerView(BRect frame)
        : BView(frame, "timer_view", B_FOLLOW_ALL, B_WILL_DRAW),
          fCounter(0),
          fMessageRunner(NULL),
          fIsRunning(false)
    {
        SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));

        BRect bounds = Bounds();

        // Counter display
        fCounterView = new BStringView(
            BRect(20, 20, bounds.right - 20, 60),
            "counter", "Counter: 0",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        fCounterView->SetFont(be_bold_font);
        fCounterView->SetFontSize(24);
        AddChild(fCounterView);

        // Queue info display
        fQueueView = new BStringView(
            BRect(20, 70, bounds.right - 20, 90),
            "queue", "Messages in queue: 0",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        AddChild(fQueueView);

        // Status display
        fStatusView = new BStringView(
            BRect(20, 100, bounds.right - 20, 120),
            "status", "Status: Stopped",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        AddChild(fStatusView);

        // Start button
        fStartButton = new BButton(
            BRect(20, 140, 120, 170),
            "start", "Start",
            new BMessage(MSG_START_TIMER),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        AddChild(fStartButton);

        // Stop button
        fStopButton = new BButton(
            BRect(130, 140, 230, 170),
            "stop", "Stop",
            new BMessage(MSG_STOP_TIMER),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        fStopButton->SetEnabled(false);
        AddChild(fStopButton);

        // Reset button
        fResetButton = new BButton(
            BRect(240, 140, 340, 170),
            "reset", "Reset",
            new BMessage(MSG_RESET_COUNTER),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        AddChild(fResetButton);

        // Info text
        BStringView* info = new BStringView(
            BRect(20, 190, bounds.right - 20, 250),
            "info",
            "This demo uses BMessageRunner to send periodic messages.\n"
            "The counter increments every second when running.\n"
            "Watch the message queue count update in real-time!",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        info->SetFontSize(10);
        AddChild(info);
    }

    ~TimerView() {
        StopTimer();
    }

    void AttachedToWindow() override {
        BView::AttachedToWindow();

        // Set this view as the target for button messages
        fStartButton->SetTarget(this);
        fStopButton->SetTarget(this);
        fResetButton->SetTarget(this);
    }

    void MessageReceived(BMessage* message) override {
        switch (message->what) {
            case MSG_START_TIMER:
                StartTimer();
                break;

            case MSG_STOP_TIMER:
                StopTimer();
                break;

            case MSG_RESET_COUNTER:
                ResetCounter();
                break;

            case MSG_TIMER_TICK:
                HandleTimerTick();
                break;

            default:
                BView::MessageReceived(message);
                break;
        }
    }

private:
    void StartTimer() {
        if (fIsRunning)
            return;

        // Create a BMessageRunner that sends MSG_TIMER_TICK every second
        BMessage timerMsg(MSG_TIMER_TICK);
        bigtime_t interval = 1000000; // 1 second in microseconds

        fMessageRunner = new BMessageRunner(
            BMessenger(this),  // Target: this view
            &timerMsg,         // Message to send
            interval,          // Interval: 1 second
            -1                 // Count: -1 means infinite
        );

        if (fMessageRunner->InitCheck() == B_OK) {
            fIsRunning = true;
            fStartButton->SetEnabled(false);
            fStopButton->SetEnabled(true);
            fStatusView->SetText("Status: Running");
        }
    }

    void StopTimer() {
        if (!fIsRunning)
            return;

        delete fMessageRunner;
        fMessageRunner = NULL;

        fIsRunning = false;
        fStartButton->SetEnabled(true);
        fStopButton->SetEnabled(false);
        fStatusView->SetText("Status: Stopped");
    }

    void ResetCounter() {
        fCounter = 0;
        UpdateDisplay();
    }

    void HandleTimerTick() {
        fCounter++;
        UpdateDisplay();
        UpdateQueueInfo();
    }

    void UpdateDisplay() {
        BString text;
        text << "Counter: " << fCounter;
        fCounterView->SetText(text.String());
    }

    void UpdateQueueInfo() {
        // Access the message queue of our window's looper
        BWindow* window = Window();
        if (window) {
            BMessageQueue* queue = window->MessageQueue();
            if (queue) {
                queue->Lock();
                int32 count = queue->CountMessages();
                queue->Unlock();

                BString text;
                text << "Messages in queue: " << count;
                fQueueView->SetText(text.String());
            }
        }
    }

    int32 fCounter;
    BMessageRunner* fMessageRunner;
    bool fIsRunning;

    BStringView* fCounterView;
    BStringView* fQueueView;
    BStringView* fStatusView;
    BButton* fStartButton;
    BButton* fStopButton;
    BButton* fResetButton;
};

class TimerWindow : public BWindow {
public:
    TimerWindow(BRect frame)
        : BWindow(frame, "Timer & Message Queue Demo",
                  B_TITLED_WINDOW,
                  B_QUIT_ON_WINDOW_CLOSE | B_NOT_RESIZABLE)
    {
        BRect viewRect = Bounds();
        TimerView* view = new TimerView(viewRect);
        AddChild(view);
    }
};

class TimerApp : public BApplication {
public:
    TimerApp()
        : BApplication("application/x-vnd.example-TimerCounter")
    {
        BRect rect(100, 100, 500, 400);
        TimerWindow* window = new TimerWindow(rect);
        window->Show();
    }
};

int main() {
    TimerApp app;
    app.Run();
    return 0;
}

BMessageRunner key parameters:

  • Target: A BMessenger pointing to the handler that will receive messages
  • Message: The BMessage to send repeatedly
  • Interval: Time between messages in microseconds (1,000,000 = 1 second)
  • Count: Number of times to send (-1 for infinite, or a positive number)
        fMessageRunner = new BMessageRunner(
            BMessenger(this), 
            &timerMsg,        
            interval,       
            -1               
        );

The message flow is as below

  1. BMessageRunner sends MSG_TIMER_TICK every second
  2. Message enters the window's BMessageQueue
  3. BLooper (the window) dispatches message to the view
  4. MessageReceived() processes the tick and updates the counter

BMessageQueue Access

BMessageQueue* queue = window->MessageQueue();
queue->Lock();
int32 count = queue->CountMessages();
queue->Unlock();

Important: Always lock the queue before accessing it! The queue is shared between threads and must be protected.

Timer Lifecycle

Starting the timer:

fMessageRunner = new BMessageRunner(...);

Stopping the timer:

delete fMessageRunner;
fMessageRunner = NULL;

The destructor automatically stops the timer and cleans up.

Compilation

gcc -o TimerCounter TimerCounter.cpp -lbe

Running the Demo

./TimerCounter

You'll see:

  • A counter starting at 0
  • Start/Stop/Reset buttons
  • Real-time queue statistics
  • Status indicator

Try this:

  • Click "Start" - counter begins incrementing

  • Watch the message queue count 

  • Click "Stop" - timer pauses

  • Click "Reset" - counter returns to 0

Advanced Concepts

Changing Timer Interval

You can modify the interval while running:

// Change to 500ms (twice as fast)
bigtime_t newInterval = 500000;
fMessageRunner->SetInterval(newInterval);

Finite Message Count

Send exactly 10 messages:

fMessageRunner = new BMessageRunner(
    BMessenger(this),
    &timerMsg,
    interval,
    10  // Stop after 10 ticks
);

Message Priority

Add priority data to your timer messages:

BMessage timerMsg(MSG_TIMER_TICK);
timerMsg.AddInt32("priority", 10);

Queue Filtering

You can filter messages before they're dispatched:

// In your BLooper subclass
void DispatchMessage(BMessage* message, BHandler* target) override {
    if (message->what == MSG_TIMER_TICK) {
        // Process timer messages specially
    }
    BLooper::DispatchMessage(message, target);
}

Common Use Cases

Animation Timer:

// 60 FPS animation
bigtime_t interval = 1000000 / 60; // ~16.6ms

Auto-save:

// Save every 5 minutes
bigtime_t interval = 5 * 60 * 1000000;
BMessage saveMsg(MSG_AUTO_SAVE);
fAutoSaver = new BMessageRunner(BMessenger(this), &saveMsg, interval);

Progress Polling:

// Check download progress every 100ms
bigtime_t interval = 100000;
BMessage pollMsg(MSG_CHECK_PROGRESS);
fPoller = new BMessageRunner(BMessenger(this), &pollMsg, interval);

Try This

  • Change the interval: Make it tick every 100ms or 5 seconds
  • Add a countdown: Start from 60 and count down to 0
  • Multiple timers: Create two BMessageRunners with different intervals
  • Pause/Resume: Implement pause that preserves the counter value
  • Queue inspection: Display the actual messages in the queue, not just the count

Performance Notes

  • BMessageRunner is efficient for periodic tasks
  • Avoid very short intervals (<10ms) for UI updates
  • Each BMessageRunner creates a separate thread internally
  • Message dispatch is asynchronous - there's no guarantee of exact timing
  • For high-precision timing, consider using BLooper::Pulse() instead

What's Next?

Now that you understand periodic messaging, the future KitLab article will explore system interactions :)

Conclusion

BMessageRunner and BMessageQueue are essential tools in the Haiku toolkit.

They enable clean, efficient periodic tasks without blocking your application's main thread.

The messaging architecture handles all the complexity of threading and synchronization, letting you focus on your application logic. Whether you're building animations, auto-save features, or real-time updates, these classes provide a robust foundation.

This is Haiku's event-driven architecture at its finest—simple to use, yet powerful enough for complex applications.

Stay tuned for the next KitLab article!


Powered by Bludit - Hosted by Planet Hoster
© 2025 Haiku Insider