2 years, 3 months ago.

How to end an event queue?

I would like to create an event queue, and then call a function ever 2 seconds for a total of 10 seconds (so likely 5 times), and then for the queue to stop executing the function. So a temporary event, but called every certain amount of time. I've tried this:

void handler(int c) {
    com.printf("Param: %d\r\n", c);
}

int main() {
    EventQueue queue;
    
    int id = queue.call_every(2000,handler, 5);
    queue.dispatch();
    
    wait(10);
    
    queue.break_dispatch();
    queue.cancel(id);
    
    while (1) { }

}

But the function doesn't stop executing.

How can I stop the function from executing after some time x?

2 Answers

2 years, 3 months ago.

Hi there,

from my point of view your code not working because after you call the dispatch method without an argument, your code is blocked in indefinitely loop. https://os.mbed.com/docs/mbed-os/v5.12/mbed-os-api-doxy/classevents_1_1_event_queue.html#a397fcb417425ebaa28c20b9e90ef3ed5

Dispatch

void handler(int c) { printf("Param: %d\r\n", c);}
 
int main() {
    printf("Start\n");
    EventQueue queue;
    int id = queue.call_every(2000,handler, 5);
    queue.dispatch(10000);
    
    while (1) {myled = !myled; wait(0.5);}
}

I do not know if these ways are correct but function will stop/pause

Cancel

void handler(int c) { printf("Param: %d\r\n", c); }
 
int main() {
    printf("Start\n");
    EventQueue queue;
    Thread t;
    t.start(callback(&queue, &EventQueue::dispatch_forever));
    int id = queue.call_every(2000,handler, 5);
    
    wait(10);
    queue.cancel(id);
    
    while (1) {myled = !myled; wait(0.5); }
}

Pause

#include "mbed.h"

DigitalOut myled(LED1);
EventQueue queue;
Thread t;
InterruptIn mybutton(USER_BUTTON);

volatile bool ispressed = true;
void pressed(){ispressed = !ispressed;}

void handler(int c) {
    if(ispressed == true){ printf("Param: %d\r\n", c); }
}
 
int main() {
    printf("Start\n");
    mybutton.rise(callback(pressed));
    t.start(callback(&queue, &EventQueue::dispatch_forever));
    int id = queue.call_every(2000,handler, 5);
    
    while (1) {myled = !myled; wait(0.5);}
}

and so on.

Best regards

J.

Accepted Answer

So I needed the queue to be bound to another thread to be able to cancel it. Thank you for your help, although it is odd how it doesn't work the same way in main().

posted by L B 03 Jun 2019
2 years, 3 months ago.

Instead of queue.call_every() use queue.call_in(), this schedules it just one time. Then reschedule it as many times as you want, and stop when needed. The function can even schedule itself if it has access to the EventQueue object.

Sorry, maybe I wasn't specific enough, but this doesn't help because at the point where I want to call the queue, the time it needs to run for is not known, which is why it is x rather than a known number.

posted by L B 03 Jun 2019