Add non blocking delay into for loop

  1. My goal is: to have a for loop in c, but leave a long delay (2-5 seconds) between each iteration of the loop. (the exact timing is non-critical, I just want to slow it down as it’s performing network functions.
  2. My actions are: I was looking at mgos_msleep() but believe it’s blocking which won’t work for that long a delay. I expect I need to use a timer but can’t work out how to do it in mos. I’ve looked online for ‘standard’ c examples but can’t find anything that’s appropriate for mos.

Why not a repeating timer which manages the number of iterations?

Not sure I quite understand what you mean?

Transform this

for(int i=0; i<10; ++i){
  // do something
  mgos_sleep(2000);
}

into something like this

struct my_struct{
  int loop_max;
  mgos_timer_id timer_id;
}

void timer_cb(void*arg){
  static int i=0;
  struct my_struct* ctx=(struct my_struct*)arg;
  if(i<ctx->loop_max){
    // do work
    i++;
  } else {
    i=0;
    mgos_clear_timer(ctx->timer_id);
    free(ctx);
  }
}
struct my_struct* ctx=(struct my_struct*)calloc(1, sizeof(*ctx));
ctx->max_loop=10;
ctx->timer_id=mgos_set_timer(2000, MGOS_TIMER_REPEAT, timer_cb, ctx);

Excellent, thanks. I was thinking about it all the wrong way round. Your example gives me a good steer in the right direction, so I think I can work out something from this.