如何使用C/C++在linux下的特定系统时间触发线程



如标题所述,如何在特定时间准确执行特定线程
有图书馆的帮助吗
例如,[00:00:00.00,00:05:10:00.00…04:00:00.00,04:05:00.00…]

这是我目前的方法,有更好的方法吗?

#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("%sn", str);
        until_next_tick(&last_tick);
    }
    return 0;
}

timer_createSIGEV_THREAD一起使用,并在timer_settime中设置重复时间,以重复的时间间隔启动新线程。

一个简单的方法是有一个while(true)循环,它调用sleep(1);,然后在循环中检查time(NULL)的时间,如果线程的时间超过了到期时间,则启动相应的线程。

一种简单的方法是使用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);
  }
}

最新更新