C语言实现定时任务

例:设置定时任务,每周周X的X时X分自动重启系统
思路:将设置好的重启时间保存到本地配置文件中,设置定时器定时一分钟,每一分钟信号触发一次事件,事件函数中获取配置文件信息与当前系统时间信息,将两个时间进行时间差计算,符合条件的自动重启系统.

//创建定时器函数(通过信号触发事件timer_task函数启动)

int create_timer()
{
    struct sigevent evp;  
    int ret = 0;

    memset(&evp, 0, sizeof(struct sigevent));

    evp.sigev_value.sival_ptr = &s_time_id;
    evp.sigev_notify = SIGEV_SIGNAL;
    evp.sigev_signo = SIGUSR1;
    signal(SIGUSR1, timer_task);
  
    ret = timer_create(CLOCK_REALTIME, &evp, &s_time_id);
    if (ret != 0) {
        printf("timer_create failed\n");  
        return -1;
	}
    return 0;
} 

//初始化定时器(设置定时时间)

int init_timer()
{
    int ret = 0;
    struct itimerspec ts;   
    ts.it_value.tv_sec = 60;
    ts.it_value.tv_nsec = 0;  
  
    ret = timer_settime(s_time_id, 0, &ts, NULL);
    if (ret != 0) {
		printf("timer_settime failed\n"); 
        return -1;
	}  
    return 0;
}

//事件函数(例如 : 固定每周X的X时X分重启)

void timer_task()  
{  
    time_t timep;
    struct tm *p;
    time(&timep);
    p = gmtime(&timep);

    AutoRebootConfig AutoRebootMsg = {0};
    config_get_auto_reboot_time(&AutoRebootMsg);	//获取配置文件中设定好的重启时间
   
    if (AutoRebootMsg.auto_reboot_enable == 1) {
        int tm_hour = p->tm_hour+8;
        if (tm_hour >= 24) {
            tm_hour -= 24;
        }
        
        //The current time is Sunday, and the automatic restart time is not Sunday
        if (p->tm_wday == 0 && AutoRebootMsg.auto_reboot_weekday != 0) {
            p->tm_wday = 7;
        }

        int weekday_sub = p->tm_wday - AutoRebootMsg.auto_reboot_weekday;
        if (p->tm_wday == AutoRebootMsg.auto_reboot_weekday || (weekday_sub == 1 && tm_hour == 0)) {
            if (tm_hour == 0 && AutoRebootMsg.auto_reboot_hour != 0) {
                tm_hour = 24;
            }    

            int time_sub = (tm_hour - AutoRebootMsg.auto_reboot_hour)*60 + p->tm_min - AutoRebootMsg.auto_reboot_minute;
            if (time_sub >= 0 && time_sub < 1) {
                system("reboot");
            }
        }
        create_timer();
        init_timer();
    }
} 
上一篇:tail: inotify cannot be used, reverting to polling: Too many open files


下一篇:万字长文 | 详解优维科技内部DevOps研发实践 | 演讲实录