• Uncategorized

About c : How-to-trigger-threads-at-specific-system-time-under-linux-with-CC

Question Detail

As mentioned in title, how can I execute the specific threads at specific time accurately?
Is there any library help to do it?
For example, [00:00:00.00, 00:05:00.00, 00:10:00.00..04:00:00.00, 04:05:00.00…]

Here is my current approach to do it, is there any better way to do it?

#include <stdio.h>
#include <unistd.h>
#include <time.h>

unsigned interval = 5*60; 

void until_next_tick(time_t *last_tick){
    time_t now = time(NULL);
    time_t next_tick = now / interval * interval + interval;
    time_t diff = next_tick - now;
    usleep(diff * 1000 * 1000);
    *last_tick = next_tick;
}
void print_current_time(char *str){
    time_t raw = time(NULL);
    struct tm *curr = localtime(&raw);
    sprintf(str, "%04d/%02d/%02d %02d:%02d:%02d", 
        curr->tm_year+1900, curr->tm_mon+1, curr->tm_mday, 
        curr->tm_hour, curr->tm_min, curr->tm_sec);
}

int main(int argc, char **argv)
{
    time_t last_tick = time(NULL);
    char str[30];
    while (1) {
        print_current_time(str);
        printf("%s\n", str);
        until_next_tick(&last_tick);
    }
    return 0;
}

Question Answer

Use timer_create with SIGEV_THREAD and set repeating time in timer_settime to start a new thread at a repeated time interval.

One simple way is to have a while(true) loop which calls sleep(1); and then in the loop checks what time it is with time(NULL) and if the time for a thread is past due, start the corresponding thread.

One simple way is using time() to get the time:

#include <stdio.h>
#include <time.h>
void *get_sys_stat(void* arg)
{
        // Do somthing hrear
}

int main()
{
  hour = 5;
  min = 30;
  int status = 0;
  time_t t = time(NULL);
  pthread_t sys_stat_thread; 
  
  while(1) {
  /* Get time*/
  struct tm tm = *localtime(&t);
     
  /* Trigger another process or thread */  
  if ((tm.tm_hour == hour) && (tm.tm_min == min))
      pthread_create(&sys_stat_thread, NULL, get_sys_stat, NULL);
  }

}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.